简体   繁体   中英

System.ArgumentOutOfRangeException occurred in C#

I am trying to extract the name of the file from a url in C#

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

I would like to get the filename as filename.abc So I did this

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

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 /. That is not going to work. You could try:

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

You need to decrement the length variable as well:

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:

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.

Add a - 1 to the end of your third line of code.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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