Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get directory name from full directory path regardless of trailing slash

Tags:

c#

.net

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?

like image 926
dimnnv Avatar asked May 22 '15 14:05

dimnnv


2 Answers

new DirectoryInfo(m_logsDir).Name;
like image 195
Matteo Umili Avatar answered Nov 03 '22 02:11

Matteo Umili


This may help

var result = System.IO.Directory.Exists(m_logsDir) ? 
              m_logsDir: 
              System.IO.Path.GetDirectoryName(m_logsDir);
like image 24
Hossein Narimani Rad Avatar answered Nov 03 '22 01:11

Hossein Narimani Rad