我试图从C#中的URL中提取文件的名称
我使用的代码如下:
string url = "https://something.something.something/something/filename.abc"); // the filename in this case should be filename.abc int firstIndex = url.lastIndexOf('/'); int length = url.Length - url.lastIndexOf('/'); string filename = url.Substring(firstIndex, length); Console.WriteLine("The name of the file is : " + filename);
但是,这将打印以下内容:文件的名称为:/filename.abc
我想得到filename.abc的文件名所以我这样做了
int firstIndex = url.lastIndexOf('/') + 1; // All the other code remains the same, and this is when the visual studio throws this error
mscorlib.dll中发生未处理的"System.ArgumentOutOfRangeException"类型异常
我该如何解决这个问题?
var fileName = "https://something.something.something/something/filename.abc"; var f = Path.GetFileName(fileName);
或者(通过这里)
var uri = new Uri("https://something.something.something/something/filename.abc"); var f = uri.Segments[uri.Segments.Length - 1];