How can I extract a substring from this string?

I am trying to extract a string at the end of a url. Example:



I am trying to get ExtractThisString.exe

from this line, however it has an unknown quantity \

. I want it to basically grab the url and list everything at the end of it.


source to share

6 answers

To find the last occurrence of a specified character, use

int pos = yourString.LastIndexOf(@"\");


then extract the substring

string lastPart = yourString.Substring(pos+1);


EDIT I am considering this answer 15 months later because I really missed a key point in the question. The OP is trying to extract the filename, not just find the last occurrence of the given character. Thus, while my answer is technically correct, it is not the best of them all, as the NET has a specialized class for handling filename and paths. This class is called Path and you can find a simple and efficient way to achieve the result using Path.GetFileName as explained in @ Adriano's answer.

I also want to highlight the fact that with the methods from the Path class, you have the advantage of code portability, because the class handles the situation when another operating system uses a different directory separator char.



Use the helper methods of the System.IO.Path class. In your case:

string fileName = Path.GetFileName(@"C:\this\that\ExtractThisString.exe");


Just for fun, if you need to do it yourself, you should start looking up the index of the last Path.DirectorySeparatorChar . If it is not the last character in the string, you can use String.Substring

to retrieve all text after this index.



try it

var str = @"C:\this\that\ExtractThisString.exe";
var filename = str.Substring(str.LastIndexOf("\\")+1);




Do it once for everything ...

public static string FileAndExtension(this string aFilePath) {
 return aFilePath.Substring(aFilePath.LastIndexOf("\\") + 1);




public static string EverythingAfterLast(this string aString, string aSeperator) {
 return aString.Substring(aString.LastIndexOf(aSeperator) + 1);





string path = @"c:\this\that\extractthisstring.exe";




I find and use this elegant way using System.IO

string file1 = Path.GetFileName(@"C:\this\that\ExtractThisString.exe");

or if you want no extension

string file2 = Path.GetFileNameWithoutExtension(@"C:\this\that\ExtractThisString.exe");

or just an extension

string ext = Path.GetExtension(@"C:\this\that\ExtractThisString.exe");



All Articles