If you have the full URL:
http://18.82.242.99/Default.aspx
and want to get only:
http://18.82.242.99
use the Uri class.
Method 1 :
string url = "http://18.82.242.99/Default.aspx";
Uri uri = new Uri(url);
string baseUrl = $"{uri.Scheme}://{uri.Authority}";
Console.WriteLine(baseUrl);
Output:
http://18.82.242.99
Method 2 :
string url = "http://18.82.242.99/Default.aspx";
Uri uri = new Uri(url);
string baseUrl = uri.GetLeftPart(UriPartial.Authority);
Console.WriteLine(baseUrl);
Output:
http://18.82.242.99
Examples
Input Output
http://18.82.242.99/Default.aspx http://183.82.242.99
https://example.com:8080/test/page.aspx https://example.com:8080
https://www.google.com/search?q=test https://www.google.com
The Uri.GetLeftPart(UriPartial.Authority) approach is generally the cleanest and safest way to extract the scheme, host, and optional port from a URL.
Sign up here with your email
ConversionConversion EmoticonEmoticon