Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting relative paths to absolute paths C#

Tags:

string

c#

path

uri

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?

like image 229
simonalexander2005 Avatar asked Dec 06 '22 02:12

simonalexander2005


1 Answers

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);
like image 171
Lee Avatar answered Dec 11 '22 08:12

Lee