Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
240 views
in Technique[技术] by (71.8m points)

c# - How can I get the last folder from a path string?

I have a directory that looks something like this:

C:UsersmeProjects

In my application, I append to that path a given project name:

C:UsersmeProjectsmyProject

After, I want to be able to pass that into a method. Inside this method I would also like to use the project name. What is the best way to parse the path string to get the last folder name?

I know a work-around would be to pass the path and the project name into the function, but I was hoping I could limit it to one parameter.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can do:

string dirName = new DirectoryInfo(@"C:UsersmeProjectsmyProject").Name;

Or use Path.GetFileName like (with a bit of hack):

string dirName2 = Path.GetFileName(
              @"C:UsersmeProjectsmyProject".TrimEnd(Path.DirectorySeparatorChar));

Path.GetFileName returns the file name from the path, if the path is terminating with then it would return an empty string, that is why I have used TrimEnd(Path.DirectorySeparatorChar)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...