应用层常规打开磁盘的方法
WCHAR szDevice[32] = L"\\\\.\\X:";
szDevice[4] = WCHAR('A' + nTempDriveNo);
HANDLE hTempDevice = CreateFile(szDevice, NULL, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
if (hTempDevice == INVALID_HANDLE_VALUE)
{
return FALSE;
}
CloseHandle(hTempDevice);
return TRUE;
当分区为隐藏分区或者只知道分区的设备名时,无法通过盘符打开磁盘设备时,可以借鉴TrueCrypt的做法,首先为设备创建一个设备链接名,然后就可以通过CreateFile直接打开,使用完之后删除该设备链接名即可,代码供上。
int FakeDosNameForDevice(LPCWSTR lpDevicePath, WCHAR *lpDosDevice, WCHAR *lpCFDevice)
{
static int g_iSeq = 1000;
swprintf(lpDosDevice, L"CnCrypt%d", g_iSeq++);
BOOL bDosLinkCreated = TRUE;
bDosLinkCreated = DefineDosDeviceW(DDD_RAW_TARGET_PATH, lpDosDevice, lpDevicePath);
if (!bDosLinkCreated)
{
return ERR_OS_ERROR;
}
swprintf(lpCFDevice, L"\\\\.\\%s", lpDosDevice);
return 0;
}
int RemoveFakeDosName(LPCWSTR lpDevicePath, LPCWSTR lpDosDevice)
{
BOOL bDosLinkRemoved = DefineDosDeviceW(DDD_RAW_TARGET_PATH | DDD_EXACT_MATCH_ON_REMOVE | DDD_REMOVE_DEFINITION, lpDosDevice, lpDevicePath);
if (!bDosLinkRemoved)
{
return ERR_OS_ERROR;
}
return 0;
}
BOOL OpenDevice(LPWSTR lpDevicePath)
{
int nDriveNo = -1;
int nStatus = ERR_SUCCESS;
HANDLE hDevice = INVALID_HANDLE_VALUE;
WCHAR szCFDevice[CC_LONG_PATH + 1] = { 0 };
WCHAR szDosDevice[CC_LONG_PATH + 1] = { 0 };
nStatus = FakeDosNameForDevice(lpDevicePath, szDosDevice, szCFDevice);
if (nStatus != ERR_SUCCESS)
{
return FALSE;
}
hDevice = CreateFile(szCFDevice, NULL, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
if (hDevice == INVALID_HANDLE_VALUE)
{
return FALSE;
}
CloseHandle(hDevice);
RemoveFakeDosName(lpDevicePath, szDosDevice);
return TRUE;
}