相关代码如下:
std::wstring path = ApplicationData::Current->LocalFolder->Path->Data();
std::wstring testFileName = path + std::wstring(L"\\TestVariablySized");
this->hMappedFile = CreateFile2(
testFileName.c_str(),
GENERIC_READ | GENERIC_WRITE,
0,
OPEN_ALWAYS,
NULL);
uint32_t checkF = GetLastError();
DISK_GEOMETRY geo = { 0 };
DWORD bReturned = 0;
bool controlCheck = DeviceIoControl(
(HANDLE)hMappedFile, // handle to device
IOCTL_DISK_GET_DRIVE_GEOMETRY, // dwIoControlCode
NULL, // lpInBuffer
0, // nInBufferSize
(LPVOID)&geo, // output buffer
(DWORD)sizeof(geo), // size of output buffer
(LPDWORD)&bReturned, // number of bytes returned
NULL);
uint32_t check = GetLastError();
此后,
controlCheck
为false,check
为ERROR_INVALID_PARAMETER
。 checkF
是ERROR_ALREADY_EXISTS
,在这里应该不是问题。据我所知,我以与
DeviceIoControl()
documentation一致的方式调用了IOCTL_DISK_GET_DRIVE_GEOMETRY
。,但显然我缺少了一些东西。非常感谢您的帮助。
编辑:
根据收到的回复,我将内容更改如下:
HANDLE hDevice = CreateFile2(
L"\\.\PhysicalDrive0",
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
OPEN_EXISTING,
NULL);
uint32_t checkF = GetLastError();
DISK_GEOMETRY geo = { 0 };
DWORD bReturned = 0;
bool controlCheck = DeviceIoControl(
hDevice, // handle to device
IOCTL_DISK_GET_DRIVE_GEOMETRY, // dwIoControlCode
NULL, // lpInBuffer
0, // nInBufferSize
(LPVOID)&geo, // output buffer
(DWORD)sizeof(geo), // size of output buffer
(LPDWORD)&bReturned, // number of bytes returned
NULL);
uint32_t check = GetLastError();
CloseHandle(hDevice);
即使还不太正确,也应该更接近正确。
checkF
是ERROR_FILE_NOT_FOUND
,我发现很奇怪。我也尝试了"\\.\PhysicalDrive1"
和"\\.\PhysicalDrive2"
,但是收到了相同的结果。 controlCheck
仍然为false,但现在检查为ERROR_INVALID_HANDLE
。 最佳答案
实际上,您并非如此,因为您没有注意本文档的这一小窍门:
您不是将句柄传递给磁盘设备,而是将句柄传递给文件系统路径。
当调用 CreateFile2()
获取磁盘设备的句柄时,您需要以\\.\PhysicalDriveX
格式而不是文件系统路径指定物理设备。
另外,正如 CreateFile2()
文档所说:
您正在使用OPEN_ALWAYS
而不是OPEN_EXISTING
。
请更仔细地阅读 CreateFile2()
文档的“物理磁盘和卷”部分。
尝试类似这样的方法:
std::wstring path = L"\\\\.\\PhysicalDrive0";
DWORD errCode;
hMappedFile = CreateFile2(
path.c_str(),
GENERIC_READ | GENERIC_WRITE,
0,
OPEN_EXISTING,
NULL);
if (this->hMappedFile == INVALID_HANDLE_VALUE)
{
errCode = GetLastError();
// handle error as needed...
}
else
{
DISK_GEOMETRY geo = { 0 };
DWORD dwReturned = 0;
bool controlCheck = DeviceIoControl(
hMappedFile, // handle to device
IOCTL_DISK_GET_DRIVE_GEOMETRY, // dwIoControlCode
NULL, // lpInBuffer
0, // nInBufferSize
&geo, // output buffer
sizeof(geo), // size of output buffer
&dwReturned, // number of bytes returned
NULL);
if (!controlCheck)
{
errCode = GetLastError();
// handle error as needed...
}
else
{
// use drive as needed...
}
CloseHandle(hMappedFile);
}