【问题标题】:C# Remove URL from StringC# 从字符串中删除 URL
【发布时间】:2010-12-01 00:35:25
【问题描述】:

这看起来很简单,但我尝试的一切似乎都不起作用

假设我有以下字符串:

string myString = "http://www.mysite.com/folder/file.jpg";

如何处理它以删除 URL 并将“file.jpg”保留为字符串值?

谢谢!

克里斯

【问题讨论】:

  • http://example.com/test.php?key=val 等情况下,您想要什么?还是http://example.com/test.htm#section1

标签: c# string


【解决方案1】:

您始终可以使用System.IO.Path 方法

string myString = "http://www.mysite.com/folder/file.jpg";
string fileName = Path.GetFileName(myString); // file.jpg

如果您确实想处理更复杂的 URI,您可以将其传递给 System.Uri 类型并获取 AbsolutePath

string myString = "http://www.mysite.com/folder/file.jpg?test=1";
Uri uri = new Uri(myString);
string file = Path.GetFileName(uri.AbsolutePath);

【讨论】:

  • 这是我最喜欢的 hack 之一 :) 一直使用它来解析网络 ID。
  • 请注意Path.GetFileName 使用的分隔符是平台相关的,因此不能保证/ 在每个可能的平台上都会出现在该集合中。 (话虽如此,我不知道任何运行 .NET 的平台不包含 /。)
  • 同时没有保证/ 是URI 的正确分隔符。依赖于平台的路径应该得到正确的斜线(注意它同时支持/ 和``)...至少在 Microsoft 版本中。
  • @Matthew:RFC2396 指定 URI 中的路径段 始终由/ 分隔。
  • (此外,如果 RFC 说要使用 /... 并不意味着所有版本的 Path.GetFileName(...) 都会处理 /
【解决方案2】:
string lastPart = myString.Substring(myString.LastIndexOf('/') + 1);

【讨论】:

    猜你喜欢
    • 2014-03-02
    • 2014-08-26
    • 2014-09-30
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 2011-12-10
    • 1970-01-01
    相关资源
    最近更新 更多