gpt4 book ai didi

c++ - 创建文件 : direct write operation to raw disk "Access is denied" - Vista, Win7

转载 作者:IT老高 更新时间:2023-10-28 22:25:08 26 4
gpt4 key购买 nike

相关的微软文档是:
Blocking Direct Write Operations to Volumes and Disks
CreateFile, remarks on Physical Disks and Volumes

可执行文件是用 C++ 编写的,它调用 CreateFile() 来打开一个没有无文件系统的 SD 卡。 CreateFile() 和连续的 ReadFile() 调用对于 GENERIC_READ 来说是成功的,没有管理员权限。

CreateFileGENERIC_WRITE 失败,即使具有管理员权限也是如此。在资源管理器中,我在属性 > 兼容性 > 权限级别下设置了以管理员身份运行。我还尝试从管理员 cmd 运行可执行文件(以 Ctrl+Shift+Enter 开头,“管理员:”在窗口标题中,适当提升)。不过,我得到 ERROR_ACCESS_DENIED (0x5)。

我是否必须将其他内容传递给 CreateFile 我不知道什么是安全属性,我只是传递 NULL,relevant code is here在第 92 行和 here在第 48 行。

或者是否应该设置其他任何东西来以管理员权限运行该进程?


一个相关问题:

Can I get write access to raw disk sectors under Vista and Windows 7 in user mode?
Raw partition access in Windows Vista
How to obtain direct access to raw HD data in C?
Is there a clean way to obtain exclusive access to a physical partition under Windows?

最佳答案

虽然@MSalters 的答案是有道理的,但这不是我的代码的工作方式。事实上,它是如此违反直觉,我花了几天时间确保代码确实有效。

这些代码片段位于经过验证的大众消费市场软件产品中。当它需要修改磁盘结构时,它会卸载 win32 卷,以便修改 NTFS 或 FAT 文件系统结构。有趣的是,卷访问句柄是只读的:

    char    fn [30];
snprintf (fn, sizeof fn, "\\\\.\\%s:", vol -> GetVolName ());

vol_handle = CreateFile (fn, GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
OPEN_EXISTING,
FILE_FLAG_NO_BUFFERING | FILE_FLAG_RANDOM_ACCESS,
NULL);

if (vol_handle == INVALID_HANDLE_VALUE)
{
// show error message and exit
}

如果无法获得对卷或分区的写入权限,如果用户在严厉警告后授权,则此代码会强制卸载:

if (!DeviceIoControl (vol_handle, FSCTL_DISMOUNT_VOLUME,
NULL, 0, NULL, 0, &status, NULL))
{
DWORD err = GetLastError ();
errormsg ("Error %d attempting to dismount volume: %s",
err, w32errtxt (err));
}

// lock volume
if (!DeviceIoControl (vol_handle, FSCTL_LOCK_VOLUME,
NULL, 0, NULL, 0, &status, NULL))
{
// error handling; not sure if retrying is useful
}

然后写入相当简单,除了将文件指针定位为 512 字节扇区:

    long    hipart = sect >> (32-9);
long lopart = sect << 9;
long err;

SetLastError (0); // needed before SetFilePointer post err detection
lopart = SetFilePointer (vol_handle, lopart, &hipart, FILE_BEGIN);

if (lopart == -1 && NO_ERROR != (err = GetLastError ()))
{
errormsg ("HWWrite: error %d seeking drive %x sector %ld: %s",
err, drive, sect, w32errtxt (err));
return false;
}

DWORD n;

if (!WriteFile (vol_handle, buf, num_sects*512, &n, NULL))
{
err = GetLastError ();
errormsg ("WriteFile: error %d writing drive %x sectors %lu..%lu: %s",
err, drv, sect, sect + num_sects - 1,
w32errtxt (err));
return false;
}

关于c++ - 创建文件 : direct write operation to raw disk "Access is denied" - Vista, Win7,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8694713/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com