Search code examples
c#asp.net

Get url without querystring


I have a URL like this:

http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye

I want to get http://www.example.com/mypage.aspx from it.

Can you tell me how can I get it?


Solution

  • You can use System.Uri

    Uri url = new Uri("http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye");
    string path = String.Format("{0}{1}{2}{3}", url.Scheme, 
        Uri.SchemeDelimiter, url.Authority, url.AbsolutePath);
    

    Or you can use substring

    string url = "http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye";
    string path = url.Substring(0, url.IndexOf("?"));
    

    EDIT: Modifying the first solution to reflect brillyfresh's suggestion in the comments.