【发布时间】:2012-09-01 12:33:18
【问题描述】:
我有一个动态生成的字符串为 /directory/folder/filename.html
如何删除最后一部分,即 /filename.html。
我希望我的输出为 /directory/folder/。
【问题讨论】:
我有一个动态生成的字符串为 /directory/folder/filename.html
如何删除最后一部分,即 /filename.html。
我希望我的输出为 /directory/folder/。
【问题讨论】:
如果你只想要路径部分使用
string result = Path.GetDirectoryName(inputName);
如果你想要文件名而不是路径
string result = Path.GetFileName(inputName);
我还看到您使用正斜杠。上述方法将在输出中为您的操作系统提供正确的文件夹分隔符(正斜杠或反斜杠)
【讨论】:
在System.IO中使用Path.GetDirectoryName方法:
string path = "/directory/folder/filename.html";
path = Path.GetDirectoryName(path);
这可能将路径分隔符更改为系统默认值。如果要保留斜线,请改用以下内容:
path = path.Substring(0, path.LastIndexOf('/'));
【讨论】:
path.LastIndexOf('/') + 1 或在结果中附加/(或Path.DirectorySeparatorChar)。
您可以使用substring不使用 IO 类/方法。
string str = "/directory/folder/filename.html";
int endIndex = str.LastIndexOf("/");
endIndex = endIndex !=-1 ? endIndex : 0;
result = str.Substring(0,endIndex);
【讨论】: