delphidelphi-xe7ioutilsdelphi-strings

TDirectory.GetDirectoryRoot does not handle correctly paths of Max_Path characters


IOUtils.TDirectory.GetDirectoryRoot(Folder) gives me an error when 'Folder' is 259 chars long (yes, it includes the \ separator at the end):

Project Tester.exe raised exception class EPathTooLongException with message 'The specified path is too long'.

I though that I can use up to 260 chars in paths.
enter image description here

Why GetDirectoryRoot does not accept paths that are of Max_Path chars?


Solution

  • And this is why:

    class procedure TDirectory.InternalCheckDirPathParam(const Path: string; const ExistsCheck: Boolean);
    begin
      TPath.CheckPathLength(Path, MAX_PATH {$IFDEF MSWINDOWS}- TFile.FCMinFileNameLen{$ENDIF});
     ...
    end;
    

    And this is the user manual for this 'wonderful' function:

    Returns the root directory for a given path.

    Use GetDirectoryRoot to obtain the root directory for a given path. Relative paths are considered relative to the application working directory. The following table lists the parameters expected by this method.

    Note: GetDirectoryRoot raises an exception if the given path is invalid or the directory does not exist.

    Thank you Embarcadeor/Idera for this high quality job!


    So, IOutils cannot be used in conjunction with Max_Path. It uses InternalCheckDirPathParam all over the place!

    The solution would be to define your own MaxPath constant:

      {$IFDEF MSWINDOWS}
        MAXPATH= MAX_PATH- 12;               { TFile.FCMinFileNameLen = 12. There is a problem in IOUtils and we cannot user Max_Path. }
      {$ELSE}
        MAXPATH= MAX_PATH;
      {$ENDIF}
    

    So, go now do a Ctrl+Shift+F and check all your code :)

    Anyway, a conflict remains: a valid path (260 chars) returned by some API call cannot be passed to IOUtils which only accepts 248 chars. If you find a better solution, let me/us know and I will accept your answer :)