I want to build a Uri based off some string values, but I'd like to avoid showing the port when I call .ToString().
var uriBuilder = new UriBuilder("http://www.google.co.uk/")
{
Path = "test"
};
The below code outputs http://www.google.co.uk:80/test instead of http://www.google.co.uk/test. Is there a way to not include the port in the final string or do I have to use one of the workarounds (such as new Uri(new Uri(baseUrl), relativePath) instead?
To achieve the result that you require you can just do like this.
var uriBuilder = new UriBuilder()
{
Scheme = "http",
Host = "www.google.co.uk",
Path = "test"
};
Uri uri = uriBuilder.Uri;
In the uri you will have the 'http://www.google.co.uk/test' result that you want.
If you check on Microsoft docs you can see that
This constructor initializes a new instance of the UriBuilder class with the Fragment, Host, Path, Port, Query, Scheme, and Uri properties set as specified in uri. If uri does not specify a scheme, the scheme defaults to "http:".
As documented here, set the Port to -1 and it will not print.
var uriBuilder = new UriBuilder("http://www.google.co.uk/")
{
Path = "test",
Port = -1
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With