2013-04-07 107 views
17

我有有如下格式的目录字符串:获取内容

C:// //你好世界

我将如何提取的最后一个/字符后的所有(世界)?

回答

27
string path = "C://hello//world"; 
int pos = path.LastIndexOf("/") + 1; 
Console.WriteLine(path.Substring(pos, path.Length - pos)); // prints "world" 

LastIndexOf方法执行相同IndexOf ..但是从字符串的结尾。

3

我会建议看看System.IO命名空间,因为它似乎你可能想要使用它。还有DirectoryInfo和FileInfo也可以在这里使用。具体DirectoryInfo's Name property

var directoryName = new DirectoryInfo(path).Name; 
9

有与路径称为Path工作静态类。

您可以通过Path.GetFileName获取完整的文件名。

你可以得到的文件名不带扩展名与Path.GetFileNameWithoutExtension

+1

我曾经想过,但要注意的是,OP似乎不把重点放在一个文件,而是一个目录 – 2013-04-07 02:51:23

9

using System.Linq;

var s = "C://hello//world"; 
var last = s.Split('/').Last(); 
1

试试这个:

string worldWithPath = "C://hello//world"; 
string world = worldWithPath.Substring(worldWithPath.LastIndexOf("/") + 1); 
+1

这是相同的解决方案已经由Simon Whitehead(http://stackoverflow.com/a/15857606/2029849)发布,除了'Substring'方法调用中明确给定的长度之外。 – abto 2017-01-14 14:07:07

+0

这是更聪明的解决方案,而不是@abto – Lali 2017-12-28 10:15:35