Extract base URl from a string in c#?

前端 未结 5 2125
情书的邮戳
情书的邮戳 2021-02-03 21:31

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 \"ht

5条回答
  •  南笙
    南笙 (楼主)
    2021-02-03 21:54

    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.

提交回复
热议问题