How to remove the port number from a url string

前端 未结 8 583
清酒与你
清酒与你 2021-02-02 04:57

I have the following code snippet:

string tmp = String.Format(\"

        
8条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-02 05:47

    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.

提交回复
热议问题