环境是Windows 7 Pro和Delphi 7。
Windows.CreateDirectory()
无法在很长的路径(该长度远低于路径长度限制)中创建多个文件夹。 GetLastError()
返回ERROR_PATH_NOT_FOUND
。
该故障在ESXi虚拟机,本机Win7工作站和物理磁盘上相同。 Windows.MoveFile()
发生类似的故障。
下面的代码中的长路径已在CMD窗口中正确创建为MKDIR
的粘贴参数。
我的解决方法是创建此漫长的零食。我将“ \”字符处的路径拆分为一个字符串数组。然后,我遍历数组并从每个元素构建累积路径。循环正确地构建了完整路径而没有错误。
我不知道为什么Win32函数无法创建有效的长路径。
var
arrDstPath : TStringArray;
begin
// --------------
// failing method
// --------------
strDstPath := 'C:\Duplicate Files\my customer recovered data\desktop\my customer name\application data\gtek\gtupdate\aupdate\channels\ch_u3\html\images\';
if (Windows.CreateDirectory(pchar(strDstPath),nil) = false) then
Result := Windows.GetLastError; // #3 is returned
if (DirectoryExists(strNewPath) = false) then
Result := ERROR_PATH_NOT_FOUND;
// -----------------
// successful method
// -----------------
strNewPath := '';
LibSplitToArray(arrDstPath,'\',strDstPath);
for intIdx := 0 to High(arrDstPath) do
begin
strNewPath := strNewPath + arrDstPath[intIdx] + '\';
Windows.CreateDirectory(PChar(strNewPath), nil);
end;
if (DirectoryExists(strDstPath) = false) then // compare to original path string
begin
Result := ERROR_PATH_NOT_FOUND;
Exit;
end;
答案 0 :(得分:7)
实际上,CreateDirectory
函数的官方文档描述了正在发生的事情。由于该函数失败,因此您的直觉应该是查看描述返回值的部分,该部分指出:
ERROR_ALREADY_EXISTS
指定的目录已经存在。
ERROR_PATH_NOT_FOUND
一个或多个中间目录不存在;该函数只会在路径中创建最终目录。
我假设您有ERROR_PATH_NOT_FOUND
,并且文档中提出了一个可能的原因:您试图一次创建该功能不支持的多个级别的子目录。
幸运的是,Delphi RTL具有ForceDirectories
函数,该函数可以递归创建子目录。 (How can I Create folders recursively in Delphi?)
在Delphi 2010和更高版本中,您还可以使用IOUtils.pas
中的TDirectory.CreateDirectory
。在内部,这称为ForceDirectories
。