Jim
Jim

Reputation: 3170

Getting the relative uri from the absolute uri

I have a System.Uri, e.g.,

var uri = new Uri("http://www.domain.com/foo/bar");

How do I get only the relative Uri out of it:

/foo/bar

Upvotes: 26

Views: 18067

Answers (2)

N Djel Okoye
N Djel Okoye

Reputation: 1080

Going the other way round, that is getting the absolute URI from the relative path:-

1.Get the directory needed. To go one step down just keep adding a \ to directory e.g. for @"c:\someDirectory\something\something\foo\bar"

if Directory.GetCurrentDirectory gives @"c:\someDirectory" then do:-

Uri uri = new Uri(Directory.GetCurrentDirectory() + 
          @"\something\something\" + relative_path);

or

Uri uri = new Uri(Directory.GetCurrentDirectory() + 
          "\\something\\something\\" + relative_path);

Without the @ symbol you will have to escape the \ character with another \ character so it reads as a string.

To go one step up instead, then get the current directory and use the Directory.GetParent method to get DirectoryInfo and keep using the parent property to keep going one step up e.g. for someDirectory\foo\bar

if Directory.GetCurrentDirectory gives @"c:\someDirectory\somthing\something" then do:-

 DirectoryInfo directory = 
     Directory.GetParent(Directory.GetCurrentDirectory()).Parent;

The GetParent takes you a step up and returns a DirectoryInfo object now you can keep using the Parent property to keep going up as you still get a DirectoryInfo everytime. So I moved up the file structure twice.

 Uri uri = new Uri(directory.FullName + relative_path);

directory.FullName is of type string which is the absolute path you want, concatenate that to your relative path and generate a new Uri. So that's a work around to go backwards.

Upvotes: 1

Scott Ivey
Scott Ivey

Reputation: 41558

What you are looking for is either Uri.AbsolutePath or Uri.PathAndQuery. PathAndQuery will include the querystring (which you don't have in your question), while AbsolutePath will give you just the path.

Console.WriteLine(uri.PathAndQuery);
// or 
Console.WriteLine(uri.AbsolutePath);

...outputs the following results for both...

/foo/bar

Upvotes: 40

Related Questions