Author: Tomas Rutkauskas
How can I extract a FileName from a URL? For example
http://www.domain.com/file.zip -> file.zip
Answer:
Solve 1:
1 function ExtractUrlFileName(const AUrl: string): string;
2 var
3 I: Integer;
4 begin
5 I := LastDelimiter('\:/', AUrl);
6 Result := Copy(AUrl, I + 1, MaxInt);
7 end;
Solve 2:
You will just have to parse the string manually, ie:
8 Filename := '../../afolder/anotherfolder/aFilename.ext';
9 Pos := LastDelimiter('/\', Filename);
10 if (Pos > 0) then
11 Filename := Copy(Pos + 1, Length(Filename) - Pos, Filename);
Solve 3:
12 Filename := '../../afolder/anotherfolder/aFilename.ext';
13 Filename := StringReplace(Filename, '/', '\', [rfReplaceAll]);
14 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.
15 function GetFilenameFromUrl(const url: string): string;
16 var
17 i: Integer;
18 begin
19 Result := EmptyStr; // be a realist, assume failure
20 i := Length(url);
21 while (i > 0) and (url[i] <> '.') do
22 dec(i);
23
24 if i = 0 then
25 Exit; // no filename separator found
26
27 if AnsiCompareText(Copy(url, i, maxint), '.exe') <> 0 then
28 Exit; // no .exe at end of url
29
30 // find next '.' before current position
31 dec(i);
32 while (i > 0) and (url[i] <> '.') do
33 dec(i);
34
35 if i = 0 then
36 Exit; // no filename separator found
37 Result := Copy(url, i + 1, maxint);
38 end;
|