Martin Reiner
Martin Reiner

Reputation: 2197

How to get the file URL from absolute path in Delphi?

I'm looking for a Delphi function which returns the file URL path from the Windows path. Is there something for it built-in in Delphi ?

Example:

Input
C:\Users\Documents\File.txt

Output
file:///C:/Users/Documents/File.txt

Thanks

Upvotes: 5

Views: 3147

Answers (2)

TLama
TLama

Reputation: 76693

You can use the UrlCreateFromPath API function.

Here is the example:

uses
  ComObj, WinInet, ShLwApi;

function FilePathToURL(const FilePath: string): string;
var
  BufferLen: DWORD;
begin
  BufferLen := INTERNET_MAX_URL_LENGTH;
  SetLength(Result, BufferLen);
  OleCheck(UrlCreateFromPath(PChar(FilePath), PChar(Result), @BufferLen, 0));
  SetLength(Result, BufferLen);
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  ShowMessage(FilePathToURL('C:\Users\Documents\File.txt'));
end;

Upvotes: 9

Remy Lebeau
Remy Lebeau

Reputation: 596256

Look at UrlCreateFromPath(). Note that there are caveats with the file: scheme, though. It is not stanardized across platforms. There are multiple formats to represent the same path in different ways, even just under Windows. Since IE4, the Win32 API standardizes on a single format, but other formats still exist.

Upvotes: 8

Related Questions