我有文件路径说“\ABC\ABX\file.pdf”。如何使用子字符串以任何其他方式仅获取文件夹路径,即“\ABC\ABX\”。
先感谢您。
使用System.IO.Path
类
var dir = Path.GetDirectoryName(@"\ABC\ABX\file.pdf");
您可以使用Substring
和的组合来执行此操作LastIndexOf
:
string path = @"\ABC\ABX\file.pdf";
string directory = path.Substring(0, path.LastIndexOf(@"\") + 1);
添加检查以确保路径甚至包含 a 也是理想的\
,并且由于+ 1
您还想检查 the\
是否已经不是最后一个字符。当然,最好一开始就不需要这样的字符串操作,但我不知道你的确切情况是什么
var directoryOnly = System.IO.Path.GetDirectoryName(@"\ABC\ABX\file.pdf")
使用 System.IO 有更好的方法来做到这一点,但纯粹是字符串操作:
string path = @"\ABC\ABX\file.pdf";
string folder = path.Substring(0, path.LastIndexOf(@"\"));
string result = test.Substring(0, test.LastIndexOf("\\") + 1);