Search code examples
delphiwinapiunicodedelphi-2009

How Do I Properly Call GetLongPathName Using Delphi 2009 and Unicode Strings?


I need to change the old Win98 short path names to long path names. I had a routine that worked fine with Delphi 4, but when I upgraded to Delphi 2009 and Unicode, it didn't work with Unicode strings.

I looked around and couldn't find a Unicode-compatible version of it.

It appears that the correct routine to use is GetLongPathName from the WinAPI. But it doesn't seem to be in the SysUtils library of Delphi 2009 and I have not been able to figure out how to declare it properly to access the WinAPI routine.

Also, it does seem that it may be tricky to call, because I've read the SO Question: Delphi TPath.GetTempPath result is cropped but that didn't help me get to first base.

Can someone please explain how to declare this function and use it properly passing a Unicode string in Delphi 2009?


Solution

  • Sure. You do need not a separate unit and can declare GetLongPathName anywhere:

    function GetLongPathName(ShortPathName: PChar; LongPathName: PChar;
        cchBuffer: Integer): Integer; stdcall; external kernel32 name 'GetLongPathNameW';
    
    function ExtractLongPathName(const ShortName: string): string;
    begin
      SetLength(Result, GetLongPathName(PChar(ShortName), nil, 0));
      SetLength(Result, GetLongPathName(PChar(ShortName), PChar(Result), length(Result)));
    end;
    
    procedure Test;
    var
      ShortPath, LongPath: string;
    begin
      ShortPath:= ExtractShortPathName('C:\Program Files');
      ShowMessage(ShortPath);
      LongPath:= ExtractLongPathName(ShortPath);
      ShowMessage(LongPath);
    end;