如何从C#中的文件路径获取子字符串?

时间:2011-02-26 13:24:23

标签: c# .net string substring filepath

我有string path = c:\inetpub\wwwrroot\images\pdf\admission.pdf

我正在使用此

path = path.LastIndexOf("\\").ToString();
path = path.Substring(path.LastIndexOf("/") + 1);

我想得到:

c:\inetpub\wwwrroot\images\pdf
c:\inetpub\wwwrroot\images\pdf\admission.pdf

现在我想从这个string path获得admission.pdf我该怎么办?

4 个答案:

答案 0 :(得分:10)

string path = "c:\\inetpub\\wwwrroot\\images\\pdf\\admission.pdf";

string folder = path.Substring(0,path.LastIndexOf(("\\")));
                // this should be "c:\inetpub\wwwrroot\images\pdf"

var fileName = path.Substring(path.LastIndexOf(("\\"))+1);
                // this should be admin.pdf

答案 1 :(得分:7)

System.IO.Path类上有一堆辅助方法,用于从字符串中提取部分路径/文件名。

在这种情况下,System.IO.Path.GetFileName会为您提供所需的内容。

答案 2 :(得分:4)

为什么选择子串?

使用

System.Io.Path.GetDirectoryName(full_filepath)

获取文件夹名称,

System.Io.Path.GetFileName(full_filepath)

仅用于文件。

答案 3 :(得分:2)

System.Io.Path.GetFileName(path);
相关问题