2009. december 27., vasárnap

Extract FileName from Url

Problem/Question/Abstract:

How can I extract a FileName from a URL?  For example http://www.domain.com/file.zip -> file.zip

Answer:

Solve 1:

function ExtractUrlFileName(const AUrl: string): string;
var
I: Integer;
begin
I := LastDelimiter('\:/', AUrl);
Result := Copy(AUrl, I + 1, MaxInt);
end;


Solve 2:

You will just have to parse the string manually, ie:

Filename := '../../afolder/anotherfolder/aFilename.ext';
Pos := LastDelimiter('/\', Filename);
if (Pos > 0) then
Filename := Copy(Pos + 1, Length(Filename) - Pos, Filename);


Solve 3:

Filename := '../../afolder/anotherfolder/aFilename.ext';
Filename := StringReplace(Filename, '/', '\', [rfReplaceAll]);
Filename := ExtractFileName(Filename);


Solve 4:

You can treat a string as an array of characters and index individual characters in it with array notation. That allows you to write a loop that checks characters starting from the end of the string and walking backwards. Once you find the start of the filename you can use the Copy function to isolate it.

function GetFilenameFromUrl(const url: string): string;
var
i: Integer;
begin
Result := EmptyStr; // be a realist, assume failure
i := Length(url);
while (i > 0) and (url[i] <> '.') do
dec(i);

if i = 0 then
Exit; // no filename separator found

if AnsiCompareText(Copy(url, i, maxint), '.exe') <> 0 then
Exit; // no .exe at end of url

// find next '.' before current position
dec(i);
while (i > 0) and (url[i] <> '.') do
dec(i);

if i = 0 then
Exit; // no filename separator found
Result := Copy(url, i + 1, maxint);
end;


Nincsenek megjegyzések:

Megjegyzés küldése