【问题标题】:How to extract file name from an Uri in C#? [duplicate]如何从 C# 中的 Uri 中提取文件名? [复制]
【发布时间】:2012-06-28 04:52:12
【问题描述】:

可能重复:
Get file name from URI string in C#

如何在 C# 中从 Uri 中提取文件名?

例如,我有一个 Uri

"http://audacity.googlecode.com/files/audacity-win-2.0.exe"

但是如何提取文件名

"audacity-win-2.0.exe"

并将其保存为字符串?

谢谢,

杰瑞

【问题讨论】:

标签: c# uri


【解决方案1】:

怎么样

Path.GetFileName(string path);

你的情况

Path.GetFileName(new Uri("http://audacity.googlecode.com/files/audacity-win-2.0.exe").AbsolutePath);

【讨论】:

  • 它不会给你任何文件名。
  • 这可能是旧的,但是对于示例使用此方法,您将在文件名上获得空字符串,因为 IsFile 仅在您提供 file:// 类型 URI 时才为真
【解决方案2】:

Path.GetFileName可以做到……

        Uri u = new Uri("http://audacity.googlecode.com/files/audacity-win-2.0.exe");
        Path.GetFileName(u.AbsolutePath);

【讨论】:

  • 这应该是公认的答案。如果你检查 uri.IsFile 会给你 false 因为不是本地文件。
【解决方案3】:

例如

Uri uri = new Uri("http://audacity.googlecode.com/files/audacity-win-2.0.exe");
string Path.GetFileName(uri.AbsolutePath);

【讨论】:

    【解决方案4】:

    假设URI 总是代表物理文件是不安全的,因此不能保证从URI 中提取文件名。

    【讨论】:

      猜你喜欢
      • 2021-08-13
      • 1970-01-01
      • 2011-05-14
      • 1970-01-01
      • 2012-02-11
      • 2021-12-16
      • 1970-01-01
      • 1970-01-01
      • 2010-11-09
      相关资源
      最近更新 更多