1

I have a dynamic generated string as /directory/folder/filename.html

How can i remove the last part i.e /filename.html.

I want my output as /directory/folder/.

4

3 回答 3

7

Use the Path.GetDirectoryName method in System.IO:

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:

path = path.Substring(0, path.LastIndexOf('/'));
于 2012-09-07T15:38:58.817 回答
3

You can use substring without using IO classes/method.

string str = "/directory/folder/filename.html";
int endIndex = str.LastIndexOf("/");
endIndex = endIndex !=-1 ? endIndex : 0;
result = str.Substring(0,endIndex);
于 2012-09-07T15:42:32.033 回答
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)

于 2012-09-07T15:38:55.733 回答