gpt4 book ai didi

c++ - SHFileOperation 无法删除文件夹

转载 作者:搜寻专家 更新时间:2023-10-31 02:21:59 25 4
gpt4 key购买 nike

我正在为 WiX 编写一个 C++ 自定义操作,它将在安装期间调用以删除安装程序安装的任何残留物。考虑以下代码:

UINT __stdcall DeleteResidue(MSIHANDLE hInstall)
{
HRESULT hr = S_OK;
UINT er = ERROR_SUCCESS;
LPWSTR lpFolderPath = NULL;
std::wstring temp;
SHFILEOPSTRUCT shFile;

hr = WcaInitialize(hInstall, "DeleteResidue");
ExitOnFailure(hr, "Failed to initialize");

hr = WcaGetProperty(L"LPCOMMAPPDATAFOLDER",&lpFolderPath);
ExitOnFailure(hr, "Failure in Finding Common App Data Folder");

temp = std::wstring(lpFolderPath);
temp+=L"\0\0";

//Stop the LPA and LPA Monitor Service. Then delete the residue.
WcaLog(LOGMSG_STANDARD, "Doing Delete Residue");

ZeroMemory(&shFile, sizeof(shFile));
shFile.hwnd = NULL;
shFile.wFunc = FO_DELETE;
shFile.pFrom = temp.c_str();
shFile.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION | FOF_NOERRORUI;
BOOL res = DirectoryExists(lpFolderPath);
if(res)
{
WcaLog(LOGMSG_STANDARD, "The directory exist");
int result = SHFileOperation(&shFile);
if(!result)
WcaLog(LOGMSG_STANDARD, "The directory should have deleted by now");
else
WcaLog(LOGMSG_STANDARD, "The directory could not be deleted.Error code %d", result);
}
else
{
WcaLog(LOGMSG_STANDARD, "It Seems the Installed Folder is No more there");
}



LExit:
er = SUCCEEDED(hr) ? ERROR_SUCCESS : ERROR_INSTALL_FAILURE;
return WcaFinalize(er);
}

在上面的代码中,我们在LPCOMMAPPDATAFOLDER 中获取C:\ProgramData。文档指出 pFrom 应该是 double null terminated。但是,代码的返回值为 0x2,即 ERROR_FILE_NOT_FOUND。上面的代码有什么问题?

最佳答案

你不是双重 nul 终止 pFrom

您有一个标准字符串(当您对其调用 .c_str() 时,它包括空终止符)。

temp = std::wstring(lpFolderPath);

然后您将一个空字符串连接到它上面:

temp+=L"\0\0";

这会使原始字符串保持不变。这是因为 std::string::operator+(const wchar_t*) 采用空终止字符串。您有 2 个空值这一事实并不重要,它只会读取第一个空值。它甚至不添加 null,因为您有效地给它的是一个空字符串,将一个空字符串连接到其他内容的结果是空操作。

有几种方法可以解决这个问题,但最简单的方法可能是更改

temp+=L"\0\0";

temp.push_back(L'\0');

它显式地向字符串添加另一个 nul,因此当您最终调用 temp.c_str() 时,您将取回所需的双 nul 终止字符串。

关于c++ - SHFileOperation 无法删除文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30842501/

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