0

When I write to a disk device or a drive, sometimes I get an access denied error:

HANDLE hd=CreateFile("\\\\.\\PhysicalDrive1",GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE, NULL,OPEN_EXISTING,FILE_FLAG_BACKUP_SEMANTICS,NULL);
//HANDLE hd=CreateFile("\\\\.\\C:",GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE, NULL,OPEN_EXISTING,FILE_FLAG_BACKUP_SEMANTICS,NULL);
WriteFile(hd,...);

The error persists even after I dismount the volume:

HANDLE hd=CreateFile("\\\\.\\PhysicalDrive1",GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE, NULL,OPEN_EXISTING,FILE_FLAG_BACKUP_SEMANTICS,NULL);
//HANDLE hd=CreateFile("\\\\.\\C:",GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE, NULL,OPEN_EXISTING,FILE_FLAG_BACKUP_SEMANTICS,NULL);
DeviceIoControl(hd,FSCTL_DISMOUNT_VOLUME,NULL,NULL,NULL,NULL,NULL,NULL);
WriteFile(hd,...);

I encountered this problem in Windows Disk Management when I tried to format a volume or delete a volume. Disk Management will show a dialog saying some process is accessing that volume and if I want to proceed. If I choose yes, the formatting or deletion can be performed without problem. I want to know how I can achieve the same in code, i.e., what API I should use to gain the write access.

3
  • 1
    Under Physical Disks and Volumes you'll find: "The caller must have administrative privileges." Commented Jul 24, 2024 at 12:26
  • @IInspectable Yes, I run the program as administrator. Commented Jul 24, 2024 at 12:29
  • 1
    According to WriteFile, the sectors you want to write fall within a mounted volume, but you don't have successfully locked or dismounted the volume. Also see stackoverflow.com/questions/6608466/…. Commented Jul 25, 2024 at 1:20

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.