我试图删除一个字符串的最后一部分,但失败。这个字符串名为D:\software\VS2012\newtext.txt
,我想修剪字符串的最后一部分所以这里newtext.txt
。我应该得到D:\software\VS2012
但是如何在c#中做到。当我尝试它时,删除所有带有'\'的字符串。这是我在c#中所做的
string str = @"D:\softwares\VS2012\newtext.txt";
str= str.Remove(str.IndexOf('\\'));
Console.WriteLine(str);
在框架中有一个预制功能
string str = @"D:\softwares\VS2012\newtext.txt";
string path = System.IO.Path.GetDirectoryName(str);
(Qazxswpoi)
请注意,您的原始代码不起作用,因为您要从第一个反斜杠中删除,而不是从最后一个反斜杠中删除。替换此行以使代码工作
Reference
尝试使用str = str.Remove(str.LastIndexOf('\\'));
:
System.IO.Path.GetDirectoryName(string)
我们也应该检查char的存在
string dirname= System.IO.Path.GetDirectoryName(@"D:\softwares\VS2012\newtext.txt");