简体   繁体   English

System.ArgumentOutOfRangeException发生在C#中

[英]System.ArgumentOutOfRangeException occurred in C#

I am trying to extract the name of the file from a url in C# 我正在尝试从C#中的URL中提取文件的名称

The code I have used is as follows: 我使用的代码如下:

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);

However, this prints the following: The name of the file is : /filename.abc 但是,这将打印以下内容:文件的名称为:/filename.abc

I would like to get the filename as filename.abc So I did this 我想将文件名作为filename.abc,所以我做到了

int firstIndex = url.lastIndexOf('/') + 1;
// All the other code remains the same, and this is when the visual studio throws this error

An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll mscorlib.dll中发生类型为'System.ArgumentOutOfRangeException'的未处理异常

How do I solve this? 我该如何解决?

var fileName = "https://something.something.something/something/filename.abc";
var f = Path.GetFileName(fileName);

Or (via here ) 或者(通过此处

var uri = new Uri("https://something.something.something/something/filename.abc");
var f = uri.Segments[uri.Segments.Length - 1];

You can do this to get the file name. 您可以执行此操作以获取文件名。

var fileName = "https://something.something.something/something/filename.abc".
Split('/').Last();

Your length parameter is the length from the beginning to the last /. 您的length参数是从开始到最后一个/的长度。 That is not going to work. 那是行不通的。 You could try: 您可以尝试:

var file = url.Substring(url.LastIndexOf("/"));

You need to decrement the length variable as well: 您还需要减少length变量:

int firstIndex = url.LastIndexOf('/') +1;
int length = url.Length - url.LastIndexOf('/')-1;

Or use the Substring(int) override that only accepts a starting parameter and reads everything from the starting point to the end: 或使用Substring(int)重写仅接受一个起始参数,并读取从起始点到结束点的所有内容:

string filename = url.Substring(firstIndex);

Simply use this- 只需使用-

using System.IO;

string url = "https://something.something.something/something/filename.abc";
string filename = Path.GetFileName(url);
Console.WriteLine("The name of the file is : " + filename);

By increasing firstIndex by 1 without adjusting the length variable by -1, you slid your substring window past the end of the string. 通过将firstIndex增加1而不将长度变量调节为-1,可以将子字符串窗口滑过字符串的末尾。

Add a - 1 to the end of your third line of code. 在第三行代码的末尾添加-1。

这将为您提供带扩展名的文件名,且不带斜杠:

var filename = url.Substring(url.LastIndexOf('/') + 1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM