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
Request.RawUrl.Split(new[] {'?'})[0];
Here's an extension method using @Kolman's answer. It's marginally easier to remember to use Path() than GetLeftPart. You might want to rename Path to GetPath, at least until they add extension properties to C#.
Usage:
Uri uri = new Uri("http://www.somewhere.com?param1=foo¶m2=bar");
string path = uri.Path();
The class:
using System;
namespace YourProject.Extensions
{
public static class UriExtensions
{
public static string Path(this Uri uri)
{
if (uri == null)
{
throw new ArgumentNullException("uri");
}
return uri.GetLeftPart(UriPartial.Path);
}
}
}
string url = "http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye";
string path = url.split('?')[0];
simple example would be using substring like :
string your_url = "http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye";
string path_you_want = your_url .Substring(0, your_url .IndexOf("?"));
System.Uri.GetComponents
, just specified components you want.
Uri uri = new Uri("http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye");
uri.GetComponents(UriComponents.SchemeAndServer | UriComponents.Path, UriFormat.UriEscaped);
Output:
http://www.example.com/mypage.aspx
Here's a simpler solution:
var uri = new Uri("http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye");
string path = uri.GetLeftPart(UriPartial.Path);
Borrowed from here: Truncating Query String & Returning Clean URL C# ASP.net