Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
685 views
in Technique[技术] by (71.8m points)

winapi - How to WriteFile to a PhysicalDrive (Windows 7) without getting ERROR_ACCESS_DENIED?

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.

First I did the following:

// from the drive letter "h:" I get the physical disk number using
// IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS => "\.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
// => ulNumberOfSectors

// now I try to write some sectors, e.g. 2 (I want to use a higher value):
WriteFile( hDevice, abBuffer, 2*512, &byteswritten, NULL );

The call to WriteFile fails with ERROR_ACCESS_DENIED.

If I write one sector, it works.

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 ERROR_ACCESS_DENIED.

I also unmounted the volume as described in CodeProject: WriteFile on Physical Drives with Windows 7 but this didn't change anything. Obviously the volume is unmounted because it's no longer visible in Windows Explorer.

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.

Any suggestions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I didn't have problems with different WriteFile() sizes, but I did solve the

WriteFile(): Access is denied <ERROR_ACCESS_DENIED/5> to '.physicaldriveX

devices (usually USB HDD/SSD) in Windows 7 running as Administrator (elevated rights) as follows:

Computer Management -> Disk Management:

  • Volume (H: in your case) -> right-click -> Delete Volume
  • Disk (Disk 2 in your case) -> right-click -> Off-line
  • Disk (Disk 2 in your case) -> right-click -> On-line

After that, I'm able to write to '.physicaldriveX' with no problem.

I think the Win7 locks (unlike previous Windows releases) the physical device as long as there is any file system on the device to avoid consistency problems.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...