Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the parent name of a URI/URL from absolute name C#

Tags:

Given an absolute URI/URL, I want to get a URI/URL which doesn't contain the leaf portion. For example: given http://foo.com/bar/baz.html, I should get http://foo.com/bar/.

The code which I could come up with seems a bit lengthy, so I'm wondering if there is a better way.

static string GetParentUriString(Uri uri)     {                     StringBuilder parentName = new StringBuilder();          // Append the scheme: http, ftp etc.         parentName.Append(uri.Scheme);                      // Appned the '://' after the http, ftp etc.         parentName.Append("://");          // Append the host name www.foo.com         parentName.Append(uri.Host);          // Append each segment except the last one. The last one is the         // leaf and we will ignore it.         for (int i = 0; i < uri.Segments.Length - 1; i++)         {             parentName.Append(uri.Segments[i]);         }         return parentName.ToString();     } 

One would use the function something like this:

  static void Main(string[] args)     {                     Uri uri = new Uri("http://foo.com/bar/baz.html");         // Should return http://foo.com/bar/         string parentName = GetParentUriString(uri);                             } 

Thanks, Rohit

like image 217
Rohit Avatar asked Feb 04 '09 06:02

Rohit


2 Answers

Did you try this? Seems simple enough.

Uri parent = new Uri(uri, ".."); 
like image 105
trypto Avatar answered Sep 21 '22 10:09

trypto


This is the shortest I can come up with:

static string GetParentUriString(Uri uri) {     return uri.AbsoluteUri.Remove(uri.AbsoluteUri.Length - uri.Segments.Last().Length); } 

If you want to use the Last() method, you will have to include System.Linq.

like image 22
Martin Avatar answered Sep 17 '22 10:09

Martin