Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract base URl from a string in c#?

Tags:

string

c#

.net

I am currently working on a project with .NET 1.1 framework and I am stuck at this point. I have a string like "http://www.example.com/mypage/default.aspx" or it might be "http://www.example.edu/mypage/default.aspx" or "http://www.example.eu/mypage/default.aspx". How can I extract the base URl from this kind of a string.

Thanks

like image 598
PushCode Avatar asked Mar 26 '13 16:03

PushCode


2 Answers

You can use URI class to get the host name.

var uri = new Uri("http://www.example.com/mypage/default.aspx");     var host = uri.Host; 

Edit You can use uri.Scheme and uri.Port to get the .Scheme e.g. (http, ftp) and .Port to get the port number like (8080)

string host = uri.Host; string scheme = uri.Scheme; int port = uri.Port; 

You can use Uri.GetLeftPart to get the base URL.

The GetLeftPart method returns a string containing the leftmost portion of the URI string, ending with the portion specified by part.

var uri = new Uri("http://www.example.com/mypage/default.aspx");     var baseUri = uri.GetLeftPart(System.UriPartial.Authority); 

The following examples show a URI and the results of calling GetLeftPart with Scheme, Authority, Path, or Query, MSDN. enter image description here

like image 110
Adil Avatar answered Sep 29 '22 23:09

Adil


Short Answer

myUri.GetLeftPart(System.UriPartial.Authority) 

Long Answer
Assuming "Base URI" means something like http://www.example.com, you can get the base uri like this:

var myUri= new Uri("http://www.example.com/mypage/default.aspx");     var baseUri = myUri.GetLeftPart(System.UriPartial.Authority) 

This gives: http://www.example.com

Note: uri.Host gives: www.example.com (not including port or scheme)

like image 22
Myster Avatar answered Sep 29 '22 22:09

Myster