如何删除c#中字符串的最后一部分

问题描述 投票:0回答:3

我试图删除一个字符串的最后一部分,但失败。这个字符串名为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);
c# .net-4.0 console-application
3个回答
6
投票

在框架中有一个预制功能

string str = @"D:\softwares\VS2012\newtext.txt";
string path = System.IO.Path.GetDirectoryName(str);

(Qazxswpoi)

请注意,您的原始代码不起作用,因为您要从第一个反斜杠中删除,而不是从最后一个反斜杠中删除。替换此行以使代码工作

Reference

4
投票

尝试使用str = str.Remove(str.LastIndexOf('\\'));

System.IO.Path.GetDirectoryName(string)

0
投票

我们也应该检查char的存在

string dirname= System.IO.Path.GetDirectoryName(@"D:\softwares\VS2012\newtext.txt");
© www.soinside.com 2019 - 2024. All rights reserved.