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

11

可能重复:
如何从C#的Uri中提取文件名?

例如,我有一个Uri

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

但是如何提取文件名呢?

"audacity-win-2.0.exe"

并将它保存为字符串?

谢谢,

Jerry


请查看我的回答 https://dev59.com/LnNA5IYBdhLWcg3wEZeT#40361205 - Ronnie Overby
4个回答

9
您可以使用

Path.GetFileName 来完成此操作:

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

这应该是被接受的答案。如果你检查uri.IsFile,会得到false,因为它不是一个本地文件。 - Arnel

6
如何呢?
Path.GetFileName(string path);

根据你的情况

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

它不会给你任何文件名,只是一个字符串。 - scegg
10
可能这已经过时了,但是使用这种方法举例,因为只有在提供file://类型的URI时,IsFile才为真,所以您会在文件名上得到空字符串。 - Alfredo Alvarez

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

0

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接