How to get a relative url from an absolute Url programmaticaly?

I'm given an absolute URL, like this: http://pc6/Surveys/Lists/Survey list

How can I take that transform it into a relative URL?

This is what I've tried, but it doesn't seem to work.

foreach (SPListItem item in itemCollections)
{
    string Url = item["URL"].ToString();
    string[] url = Url.Split(',');
    var listUrl = url[0];  //Here I Got Absolute Url  
}

Upvotes: 0

Views: 5956

Answers (1)

Matthew Haugen
Matthew Haugen

Reputation: 13286

I guess it depends on what you want it relative to, but assuming you're just looking for an absolute path...

string absolute = "http://example.com/this/is/a/test";

string rel = new Uri(absolute).AbsolutePath;

or with the query,

string rel = new Uri(absolute).PathAndQuery;

Admittedly I'm also a little confused about your attempt. Why are you splitting by a comma? Are we, perhaps, not on the same page about what a relative path should look like? In any event, this should do it.

Upvotes: 4

Related Questions