-1

我有文件路径说“\ABC\ABX\file.pdf”。如何使用子字符串以任何其他方式仅获取文件夹路径,即“\ABC\ABX\”。

先感谢您。

4

5 回答 5

6

使用System.IO.Path

var dir = Path.GetDirectoryName(@"\ABC\ABX\file.pdf");
于 2013-05-20T09:20:46.220 回答
1

您可以使用Substring和的组合来执行此操作LastIndexOf

string path = @"\ABC\ABX\file.pdf";
string directory = path.Substring(0, path.LastIndexOf(@"\") + 1);

添加检查以确保路径甚至包含 a 也是理想的\,并且由于+ 1您还想检查 the\是否已经不是最后一个字符。当然,最好一开始就不需要这样的字符串操作,但我不知道你的确切情况是什么

于 2013-05-20T09:21:45.660 回答
1

您正在寻找Path.GetDirectoryName

var directoryOnly = System.IO.Path.GetDirectoryName(@"\ABC\ABX\file.pdf")

现场示例:http ://rextester.com/WDVD42852

于 2013-05-20T09:21:51.573 回答
0

使用 System.IO 有更好的方法来做到这一点,但纯粹是字符串操作:

string path = @"\ABC\ABX\file.pdf";
string folder = path.Substring(0, path.LastIndexOf(@"\"));
于 2013-05-20T09:22:04.617 回答
0
string result = test.Substring(0, test.LastIndexOf("\\") + 1);
于 2013-05-20T09:22:24.307 回答