"blahblah\dummytext\_config.bat"
如果我想从这个字符串中获取 _config.bat,最好的方法是什么?我能想到的唯一方法是从 .bat 读回它找到的第一个斜杠,但我不知道该怎么做。
最佳答案
您可以使用 LastIndexOf 方法找到最后一个反斜杠:
int index = myString.LastIndexOf( @"\" );
string result = myString.SubString( index + 1 );
丹尼尔说得有道理。使用 FileInfo 将是一种更安全且易于使用的方法:
// myString doesn't need a full path either
System.IO.FileInfo fi = new System.IO.FileInfo( myString );
// returns just the file name without the path
string result = fi.Name;
还有agent-j的提示:
string result = System.IO.Path.GetFileName( myString );
我不确定 Path 是否需要完整路径。 FileInfo 和 Path 也接受不存在的路径和文件名。
关于c# - 你能在正则表达式中向后阅读吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6511375/