How to get the parts of a URL in ASP.NET

June 30, 2009 – 8:43 pm

Every time I need to parse a URL or to extract parts of a URL in ASP.NET C# I can never remember what I did last time and need to refer to the documentation. So, in order to quickly answer the question “How can I get the elements of a URL in C#?”, I’ve made this quick reference.

Uri uri = new Uri("http://www.contoso.com:8080/catalog
/shownew.htm?date=today");
Response.Write("AbsoluteUri: " + uri.AbsoluteUri);
Response.Write("Scheme: " + uri.Scheme);
Response.Write("Host: " + uri.Host);
Response.Write("Port: " + uri.Port);
Response.Write("AbsolutePath: " + uri.AbsolutePath);
Response.Write("PathAndQuery: " + uri.PathAndQuery);
Response.Write("Query: " + uri.Query);
string[] segments = uri.Segments;
foreach (string s in segments)
{
    Response.Write("Segment: " + s);
}
Response.Write("Authority: " + uri.Authority);
Response.Write("HostNameType: " + uri.HostNameType.ToString());
Response.Write("IsDefaultPort: " + uri.IsDefaultPort.ToString());
Response.Write("IsFile: " + uri.IsFile.ToString());

The output:

AbsoluteUri: http://www.contoso.com:8080/catalog/shownew.htm?date=today
Scheme: http
Host: www.contoso.com
Port: 8080
AbsolutePath: /catalog/shownew.htm
PathAndQuery: /catalog/shownew.htm?date=today
Query: ?date=today
Segment: /
Segment: catalog/
Segment: shownew.htm
Authority: www.contoso.com:8080
HostNameType: Dns
IsDefaultPort: False
IsFile: False

Your Ad Here

Post a Comment