If you would like to discuss anything, please contact me via email: Howard.Bayliss@sequence.co.uk

Wednesday, November 9, 2011

Remove query string from url

I needed to delete the querystring value from a Url. The code I used to do this is right at the end of this post.

First though, here's the reason I needed to do it.

I found that if you call the SPWeb.GetFile method, with a Url that contains a query string, the value of Item for the returned SPFile will be null. Here's an example:


string url = "http://red-hb:8080/TestSite/Pages/Tamar.aspx?x=y";

using (SPSite site = new SPSite(url))
{
using (SPWeb web = site.OpenWeb())
{
SPFile file = web.GetFile(url);
Console.Write(file.Item["Title"]); // Item will be null.
}
}


OK, here's how I removed the query string:


string url = "http://red-hb:8080/TestSite/Pages/Tamar.aspx?x=y";

Uri uri = new Uri(url);

string queryString = uri.Query;

if (String.IsNullOrEmpty(queryString) == false)
{
url = url.Replace(uri.Query, String.Empty);
}

No comments:

Post a Comment