“NUL”上的UWP CreateFile2 ERROR_ACCESS_DENIED

时间:2017-06-13 14:26:33

标签: c++ uwp windows-10-universal createfile

我正在尝试将一些旧的东西从WP8迁移到具有C ++扩展的通用Windows平台。当我尝试使用此代码时问题就出现了

HANDLE h = CreateFile(L"NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);

h为-1,最后一个错误为5(ERROR_ACCESS_DENIED) CreateFile以这种方式重新定义:

HANDLE CreateFile(
_In_ LPCWSTR lpFileName,
_In_ DWORD dwDesiredAccess,
_In_ DWORD dwShareMode,
_In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes,
_In_ DWORD dwCreationDisposition,
_In_ DWORD dwFlagsAndAttributes,
_In_opt_ HANDLE hTemplateFile
)
{
    CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
    extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
    extendedParameters.dwFileAttributes = dwFlagsAndAttributes & 0x0003FFF7;
    extendedParameters.dwFileFlags = dwFlagsAndAttributes & 0xFF3C0000;
    extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
    extendedParameters.lpSecurityAttributes = lpSecurityAttributes;
    extendedParameters.hTemplateFile = hTemplateFile;
    return CreateFile2(lpFileName, dwDesiredAccess, dwShareMode, 
dwCreationDisposition, &extendedParameters);
}

此代码适用于Windows Phone 8,但在Windows 10上不起作用。因此,问题是 - 我做错了什么。

1 个答案:

答案 0 :(得分:0)

这里有两个问题。首先,正如CreateFile2 function

中所述
  

从Windows应用商店应用调用时, CreateFile2 已简化。您只能在 ApplicationData.LocalFolder Package.InstalledLocation 目录中打开文件或目录。您无法打开命名管道或邮箱或创建加密文件( FILE_ATTRIBUTE_ENCRYPTED )。

因此,在UWP中使用CreateFile2函数时,我们需要在ApplicationData.LocalFolderPackage.InstalledLocation目录中提供lpFileName参数的路径,而不仅仅是文件名:

Windows::Storage::StorageFolder^ localFolder = Windows::Storage::ApplicationData::Current->LocalFolder;
String^ path = localFolder->Path;
path += L"\\Test.txt";

CREATEFILE2_EXTENDED_PARAMETERS extendedParams;
extendedParams.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
extendedParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
extendedParams.dwFileFlags = FILE_FLAG_SEQUENTIAL_SCAN;
extendedParams.dwSecurityQosFlags = SECURITY_ANONYMOUS;
extendedParams.lpSecurityAttributes = NULL;
extendedParams.hTemplateFile = NULL;

HANDLE fileHandle = CreateFile2(path->Data(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, OPEN_ALWAYS, &extendedParams);

第二个是我们不能使用NUL作为文件名。见Naming Files, Paths, and Namespaces

  

请勿对文件名使用以下保留名称:

     

CON,PRN,AUX, NUL ,COM1,COM2,COM3,COM4,COM5,COM6,COM7,COM8,COM9,LPT1,LPT2,LPT3,LPT4,LPT5,LPT6,LPT7, LPT8和LPT9   同时避免使用这些名称后立即进行扩展;例如,不建议使用NUL.txt。有关详细信息,请参阅Namespaces

因此,您可以像下面那样更改代码,然后就不应该出错。

Windows::Storage::StorageFolder^ localFolder = Windows::Storage::ApplicationData::Current->LocalFolder;
String^ path = localFolder->Path;
path += L"\\Test.txt"; //Replace with the name you want to use.

HANDLE h = CreateFile(path->Data(), 0, 0, NULL, OPEN_ALWAYS, 0, NULL);