Wednesday, March 16, 2011

C# Get RelativeUrl from AbsoluteUrl

Getting relativeUrl from absoluteUrl is very simple.

We have a class System.Uri which takes absolute/full url as a parameter and gives the relative url.
using System;
private static string GetRelativeUrl(string fullUrl)
{
try
{
Uri uri = new Uri(fullUrl);//fullUrl is absoluteUrl
string relativeUrl = uri.AbsolutePath;//The Uri property AbsolutePath gives the relativeUrl

return relativeUrl;
}
catch (Exception ex)
{
return fullUrl;
//throw ex;
}
}

5 comments:

  1. Exactly what I was looking for, thanks!

    ReplyDelete
  2. Starting SharePoint 2013, you can use SPWeb.GetServerRelativeUrlFromUrl() method which accepts a full, server-relative or site-relative URL as a parameter and returns the server-relative URL.

    ReplyDelete
  3. Really helpful and i got it fixed..

    ReplyDelete
  4. Also can you help how to I get Site URL from the Absolute URL

    ReplyDelete