简体   繁体   中英

Getting the relative uri from the absolute uri

I have a System.Uri, eg,

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

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

/foo/bar

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

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 eg 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 eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM