Win32 CreateDirectory 因长路径中的多个文件夹而失败

Bru*_*vin 1 delphi create-directory

环境是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;
Run Code Online (Sandbox Code Playgroud)

And*_*and 8

实际上,该CreateDirectory函数的官方文档描述了正在发生的事情。由于函数失败,您的直觉应该是查看描述返回值的部分,其中指出:

ERROR_ALREADY_EXISTS

指定的目录已经存在。

ERROR_PATH_NOT_FOUND

一个或多个中间目录不存在;此函数只会在路径中创建最终目录。

我假设您有ERROR_PATH_NOT_FOUND,并且文档提出了一个可能的原因:您试图一次创建多个级别的子目录,该功能不支持。

幸运的是,Delphi RTL 具有ForceDirectories递归创建子目录的功能。(如何在 Delphi 中递归创建文件夹?

在 Delphi 2010 及更高版本中,您还可以使用TDirectory.CreateDirectoryfrom IOUtils.pas. 在内部,这会调用ForceDirectories.