IITmadras
IITmadras

Reputation: 21

substring function in c# throwing exception

My string is delete filename (filename )which i would give at run time this string is str3 I want only the filename(no matter what length it is). Here is my code:

int len = str3.Length;
string d = str3.Substring(6,len-1);// 6 for delete index and to get rest word is len -1
Console.Write(d);

But It is throwing me an exception.

Upvotes: 0

Views: 1530

Answers (4)

Chris Dunaway
Chris Dunaway

Reputation: 11216

If you only want the file name, just use the GetFileName method of the Path class in the System.IO namespace:

string d = System.IO.Path.GetFileName(str3);

Upvotes: 0

Ben
Ben

Reputation: 764

Since you're not telling us what the exception is, I'm going to assume that it's from the length being less than the substring starting point. Before you do

str3.Substring(6,len-6)

you should first check

if (str3.Length > 6)

so it looks like

int len=str3.Length;
if (str3.Length > 6)
    string d = str3.Substring(6,len-6);
Console.Write(d);

Also note that it's len-6 since that refers to the count, not the last index. The second param for String.Substring also isn't necessary. It goes to the end of the String by default as you can read here.

Upvotes: 0

DotNetUser
DotNetUser

Reputation: 6612

Do this

  str3.Substring(6,(len-6));

Second argument is number of characters in the substring, so if you start at index 6 and you want everything after that point you would subtract startindex from the length.

Upvotes: 0

Matt Grande
Matt Grande

Reputation: 12157

Substring expects the length of the rest of the string (ie, the number of characters to grab). Try this:

string d = str3.Substring(6, len-7);

EDIT - As CodeCaster reminded me, if you're grabbing the whole remainder of the string, you don't need to include the length.

string d = str3.Substring( 6 );

Upvotes: 4

Related Questions