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

时间:2012-09-07 15:36:43

标签: c# html xml

我有一个动态生成的字符串/directory/folder/filename.html

如何删除最后一部分,即/filename.html。

我希望输出为/ directory / folder /.

3 个答案:

答案 0 :(得分:7)

使用System.IO中的Path.GetDirectoryName方法:

string path = "/directory/folder/filename.html";
path = Path.GetDirectoryName(path);

可能将路径分隔符更改为系统默认值。如果要保留斜杠,请改用以下内容:

path = path.Substring(0, path.LastIndexOf('/'));

答案 1 :(得分:3)

您可以使用substring 而无需使用IO类/方法

string str = "/directory/folder/filename.html";
int endIndex = str.LastIndexOf("/");
endIndex = endIndex !=-1 ? endIndex : 0;
result = str.Substring(0,endIndex);

答案 2 :(得分:2)

如果您只想使用路径部分

string result = Path.GetDirectoryName(inputName);

如果你想要文件名而不是路径

string result = Path.GetFileName(inputName);

我也看到你使用正斜杠。上面的方法将在输出中为您的操作系统(正斜杠或反斜杠)提供正确的文件夹分隔符