title: Getting the parent name of a URI/URL from absolute name C#
body: <p>Given an absolute URI/URL, I want to get a URI/URL which doesn't contain the leaf portion. For example: given <a href="http://foo.com/bar/baz.html" rel="noreferrer">http://foo.com/bar/baz.html</a>, I should get <a href="http://foo.com/bar/" rel="noreferrer">http://foo.com/bar/</a>.</p>
  
  <p>The code which I could come up with seems a bit lengthy, so I'm wondering if there is a better way.</p>
  
  <pre><code>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 &lt; uri.Segments.Length - 1; i++)
          {
              parentName.Append(uri.Segments[i]);
          }
          return parentName.ToString();
      }
  </code></pre>
  
  <p>One would use the function something like this:</p>
  
  <pre><code>  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);                        
      }
  </code></pre>
  
  <p>Thanks,
  Rohit</p>