title: How to WriteFile to a PhysicalDrive (Windows 7) without getting ERROR_ACCESS_DENIED?
body: <p>I'm trying to write a test pattern to every sector of a formatted USB drive. There is one logical drive (e.g. h:). This volume is FAT-formatted and contains data to be overwritten. Also, I want to overwrite the whole physical drive. The program is running with elevated user rights. </p>
  
  <p>First I did the following:</p>
  
  <pre><code>// from the drive letter "h:" I get the physical disk number using
  // IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS =&gt; "\\.\PhysicalDrive2"
  
  hDevice = ::CreateFile( "\\.\PhysicalDrive2", GENERIC_READ|GENERIC_WRITE, 
    FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL ); 
  
  // get the number of available sectors with IOCTL_DISK_GET_DRIVE_GEOMETRY_EX
  // =&gt; ulNumberOfSectors
  
  // now I try to write some sectors, e.g. 2 (I want to use a higher value):
  WriteFile( hDevice, abBuffer, 2*512, &amp;byteswritten, NULL );
  </code></pre>
  
  <p>The call to <code>WriteFile</code> fails with <code>ERROR_ACCESS_DENIED</code>.</p>
  
  <p>If I write one sector, it works.</p>
  
  <p>When I overwrite the first sector and plug the device out and in again, Windows wants to format it. In this situation my code with 2048 sectors at once works without <code>ERROR_ACCESS_DENIED</code>.</p>
  
  <p>I also unmounted the volume as described in <a href="http://www.codeproject.com/Answers/97356/WriteFile-on-Physical-Drives-with-Windows-7/?cmt=7750#answer2" rel="noreferrer">CodeProject: WriteFile on Physical Drives with Windows 7</a> but this didn't change anything. Obviously the volume is unmounted because it's no longer visible in Windows Explorer.</p>
  
  <p>I want to write more than a single sector due to perfomance reasons. I'm also afraid that other problems in the field might occur because I don't fully understand ths problem.  </p>
  
  <p>Any suggestions?</p>