0

Possible Duplicate:
Conversion between absolute and relative paths in Delphi

I'm trying to figure out how to get a file path based on an original web link. In my application, I have two values:

fRootDir: String = C:\Some Directory\My Web Site\ (Application directory)

fImgPath: String = ../Some Other Web Site/SomeImage.jpg (From a web page)

Result needs to be: C:\Some Directory\Some Other Web Site\SomeImage.jpg

Notice the ../ in front of the image path. This could be many in a row like ../../../ which each ../ means go up a folder. The image SomeImage.jpg is in fact a location at C:\Some Directory\Some Other Web Site\.

Also note that web links use / - which is not a problem to convert to \. The problem is with noticing .. and actually looking in the above directory for each.

Now I need to combine the two properties to result in a final path of where to find SomeImage.jpg on the computer, based on the root and the image paths.

Community
  • 1
  • 1
Jerry Dodge
  • 26,858
  • 31
  • 155
  • 327
  • @Serg Actually thanks for pointing that out, I found better answers there, but the ones here are still good because they're short and simple :D – Jerry Dodge Dec 11 '11 at 00:17

2 Answers2

3

This is very easy using the PathCanonicalize SHLWAPI function.

Just do

function SimplifyPath(const Path: string): string;
var
  buf: array[0..MAX_PATH - 1] of char;
begin
  if PathCanonicalize(buf, PChar(Path)) then
    result := buf
  else
    RaiseLastOSError;
end;
Andreas Rejbrand
  • 105,602
  • 8
  • 282
  • 384
  • I don't understand - there's only one parameter? I have two different strings to pass into this function: Root Path (C:\SomeFolder\) and Relative Path (../SomeOtherFolder/SomeFile.abc) - the two need to be combined. I don't see how this function can accomplish this. – Jerry Dodge Dec 10 '11 at 23:37
  • `SimplifyPath(RootPath + RelativePath)` – Andreas Rejbrand Dec 10 '11 at 23:39
3

Even simpler:

const
  RootFolder = 'D:\PerforceThuis\Marjan\Probeersels\StackOverflow';
  RelativeFolder = '..\..\General\Plugins';
begin
  WriteLn(ExpandFileName(IncludeTrailingBackSlash(RootFolder)+RelativeFolder));

Tested in D6. Outputs:

D:\PerforceThuis\Marjan\General\Plugins
Marjan Venema
  • 19,136
  • 6
  • 65
  • 79