Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

string - Get the (last part of) current directory name in C#

I need to get the last part of current directory, for example from /Users/smcho/filegen_from_directory/AIRPassthrough, I need to get AIRPassthrough.

With python, I can get it with this code.

import os.path

path = "/Users/smcho/filegen_from_directory/AIRPassthrough"
print os.path.split(path)[-1]

Or

print os.path.basename(path)

How can I do the same thing with C#?

ADDED

With the help from the answerers, I found what I needed.

using System.Linq;
string fullPath = Path.GetFullPath(fullPath).TrimEnd(Path.DirectorySeparatorChar);
string projectName  = fullPath.Split(Path.DirectorySeparatorChar).Last();

or

string fullPath = Path.GetFullPath(fullPath).TrimEnd(Path.DirectorySeparatorChar);
string projectName = Path.GetFileName(fullPath);
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

You could try:

var path = @"/Users/smcho/filegen_from_directory/AIRPassthrough/";
var dirName = new DirectoryInfo(path).Name;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...