c# - 从 C# 中的字符串中提取基本 URl?

标签 c# .net string

我目前正在使用 .NET 1.1 框架开发一个项目,但我被困在了这一点上。我有一个类似“http://www.example.com/mypage/default.aspx”的字符串,或者它可能是“http://www.example.edu/mypage/default.aspx”或“http://www.example.eu/mypage/default.aspx”。我怎样才能从这种字符串中提取基本 URl。

谢谢

最佳答案

您可以使用 URI获取主机名的类。

var uri = new Uri("http://www.example.com/mypage/default.aspx");    
var host = uri.Host;

编辑 您可以使用uri.Schemeuri.Port获取 .Scheme 例如(http, ftp) 和 .Port 获取端口号,如 (8080)

string host = uri.Host;
string scheme = uri.Scheme;
int port = uri.Port;

您可以使用 Uri.GetLeftPart获取基本 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);

以下示例显示了一个 URI 以及使用 Scheme、Authority、Path 或 Query 调用 GetLeftPart 的结果,MSDN . enter image description here

关于c# - 从 C# 中的字符串中提取基本 URl?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15641797/

相关文章:

java - 在 Java 中将对象与字符串相互转换的公认做法?

c# - 在 C# 中提取 2 个图像之间的差异

c# - 从 SQLDataSource 修改日期/时间

c# - 字符 Å Ä Ö 没有显示在我的 DDL 中,我如何告诉 restclient 使用特定的字符集?

c# - MonoMac 中 NSApplication 的子类

c# - 捕捉和重新抛出 .NET 异常的最佳实践

.net - Azure AD Microsoft 帐户客户端是公共(public)的,因此不应显示 'client_assertion' 和 'client_secret'

c# - 分布式窗口服务

string - SWIFT:为什么 "NSURL(string:"返回 Nil,即使它在浏览器中是有效的 url?

java - 如何在Java中反转字符串