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.
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 );
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 .
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.
如果只需要文件名,则只需使用System.IO命名空间中Path类的GetFileName方法:
string d = System.IO.Path.GetFileName(str3);
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.