I have a dynamic generated string as /directory/folder/filename.html
我有一个动态生成的字符串as /directory/folder/filename.html
How can i remove the last part i.e /filename.html.
如何删除最后一部分i。e / filename.html。
I want my output as /directory/folder/.
我希望输出为/directory/folder/。
3 个解决方案
#1
6
Use the Path.GetDirectoryName
method in System.IO
:
使用的路径。GetDirectoryName方法先:
string path = "/directory/folder/filename.html";
path = Path.GetDirectoryName(path);
This may change the path seperator to the system default. If you want to preserve the slashes, use the following instead:
这可能会改变路径seperator到系统默认值。如果你想保存斜杠,可以使用以下文字:
path = path.Substring(0, path.LastIndexOf('/'));
#2
3
You can use substring
without using IO classes/method.
您可以使用子字符串而不用IO类/方法。
string str = "/directory/folder/filename.html";
int endIndex = str.LastIndexOf("/");
endIndex = endIndex !=-1 ? endIndex : 0;
result = str.Substring(0,endIndex);
#3
2
If you want only the path part use
如果您只想使用路径部分
string result = Path.GetDirectoryName(inputName);
If you want the filename and not the path
如果您想要文件名而不是路径
string result = Path.GetFileName(inputName);
Also I see that you use the forward slash. The methods above will give in output a folder separator correct for your operating system (forward or back slashes)
我还看到你用了正斜线。上面的方法将为您的操作系统(向前或向后斜杠)输出一个文件夹分隔符。
#1
6
Use the Path.GetDirectoryName
method in System.IO
:
使用的路径。GetDirectoryName方法先:
string path = "/directory/folder/filename.html";
path = Path.GetDirectoryName(path);
This may change the path seperator to the system default. If you want to preserve the slashes, use the following instead:
这可能会改变路径seperator到系统默认值。如果你想保存斜杠,可以使用以下文字:
path = path.Substring(0, path.LastIndexOf('/'));
#2
3
You can use substring
without using IO classes/method.
您可以使用子字符串而不用IO类/方法。
string str = "/directory/folder/filename.html";
int endIndex = str.LastIndexOf("/");
endIndex = endIndex !=-1 ? endIndex : 0;
result = str.Substring(0,endIndex);
#3
2
If you want only the path part use
如果您只想使用路径部分
string result = Path.GetDirectoryName(inputName);
If you want the filename and not the path
如果您想要文件名而不是路径
string result = Path.GetFileName(inputName);
Also I see that you use the forward slash. The methods above will give in output a folder separator correct for your operating system (forward or back slashes)
我还看到你用了正斜线。上面的方法将为您的操作系统(向前或向后斜杠)输出一个文件夹分隔符。