简体   繁体   中英

Get directory name from full directory path regardless of trailing slash

I need to get the directory name from its path regardless of any of having a trailing backslash. For example, user may input one of the following 2 strings and I need the name of logs directory:

"C:\Program Files (x86)\My Program\Logs"
"C:\Program Files (x86)\My Program\Logs\"

None of the following gives correct answer ( "Logs" ):

Path.GetDirectoryName(m_logsDir);
FileInfo(m_logsDir).Directory.Name;

They apparently analyze the path string and in the 1st example decide that Logs is a file while it's really a directory.

So it should check if the last word ( Logs in our case) is really a directory; if yes, return it, if no (Logs might be a file too), return a parent directory. If would require dealing with the actual filesystem rather than analyzing the string itself.

Is there any standard function to do that?

new DirectoryInfo(m_logsDir).Name;

This may help

var result = System.IO.Directory.Exists(m_logsDir) ? 
              m_logsDir: 
              System.IO.Path.GetDirectoryName(m_logsDir);

For this we have a snippet of code along the lines of:

m_logsDir.HasFlag(FileAttribute.Directory); //.NET 4.0

or

(File.GetAttributes(m_logsDir) & FileAttributes.Directory) == FileAttributes.Directory; // Before .NET 4.0

Let me rephrase my answer, because you have two potential flaws by the distinguishing factors. If you do:

var additional = @"C:\Program Files (x86)\My Program\Logs\";
var path = Path.GetDirectoryName(additional);

Your output would be as intended, Logs . However, if you do:

var additional = @"C:\Program Files (x86)\My Program\Logs";
var path = Path.GetDirectoryName(additional);

Your output would be My Program , which causes a difference in output. I would either try to enforce the ending \\ otherwise you may be able to do something such as this:

var additional = @"C:\Program Files (x86)\My Program\Logs";
var filter = additional.Split('\\');
var getLast = filter.Last(i => !string.IsNullOrEmpty(i));

Hopefully this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM