How to remove the port number from a url string

Use the Uri.GetComponents method. To remove the port component you'll have to combine all the other components, something like:

var uri = new Uri( "http://www.example.com:80/dir/?query=test" );
var clean = uri.GetComponents( UriComponents.Scheme | 
                               UriComponents.Host | 
                               UriComponents.PathAndQuery, 
                               UriFormat.UriEscaped );

EDIT: I've found a better way:

var clean = uri.GetComponents( UriComponents.AbsoluteUri & ~UriComponents.Port,
                               UriFormat.UriEscaped );

UriComponents.AbsoluteUri preservers all the components, so & ~UriComponents.Port will only exclude the port.


UriBuilder u1 = new UriBuilder( "http://www.example.com:80/dir/?query=test" );
u1.Port = -1;
string clean = u1.Uri.ToString();

Setting the Port property to -1 on UriBuilder will remove any explicit port and implicitly use the default port value for the protocol scheme.