tags:

views:

97

answers:

3

Hi,

I have a program that trawls html files and finds href tags, takes the string inside (the link), and converts it to the file location.

The problem comes when the href tag uses relative links, eg:

<a href="../../../images/arrow.gif"/>

In that case, my program returns:

\\server\webroot\folder\foo\bar\mew\..\..\..\images\arrow.gif

for example (because it doesn't start with "http", it appends the path of the file it's in to the start).

This, obviously, can be simplified to:

\\server\webroot\folder\images\arrow.gif

Is there an object that can do this kind of simplification, or do I need to do some string parsing - and if so what's the best way?

+2  A: 

I assume you're using ASP.NET here. In this case, I think you simply want the Server.MapPath function to return the actual physical URI of the file.

var absoluteUrl = this.Server.MapPath("../../../images/arrow.gif");
// absoluteUrl = "\\server\webroot\folder\images\arrow.gif"

(this refers to the current page of course. You can always use HttpContext.Current.Server instead, if that's not available for whatever reason.)

Note: If you want to do things manually and you already have a specific string like "\server\webroot\folder\", then the functionality of System.IO.Path should do the job I would think:

var absoluteUri = Path.GetFullPath(Path.Combine("\\server\webroot\folder\",
    "../../../images/arrow.gif"));
Noldorin
actually i'm just using plain old C# and scanning the source code manually...
simonalexander2005
See my update, in that case. :)
Noldorin
Path.GetFullPath("\\server\webroot\folder\foo\bar\mew\..\..\..\images\arrow.gif") does the job - great, thanks :)
simonalexander2005
A: 

Check out the obvious candidates:

  • Path
  • DirectoryInfo

I bet they have some method to do this. Guess: Create a new DirectoryInfo object for your path and then check the properties - probably canonical path in there somewhere...

Daren Thomas
+2  A: 

You can use the Uri class to combine them:

Uri root = new Uri(@"\\server\webroot\folder\foo\bar\mew\", UriKind.Absolute);
Uri relative = new Uri("../../../images/arrow.gif", UriKind.Relative);

Uri comb = new Uri(root, relative);
Lee