Get the directory name from the full directory path, regardless of the trailing slash

I need to get the directory name from my path, regardless of which one has a backslash. For example, a user can enter one of the following two lines, and I need the name of the log directory:

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

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

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

They apparently analyze the path string, and in the first example we decide that Logs is a file, while it really is a directory.

Therefore, he must check whether the last word ( Logs in our case) is really a directory; if yes, return it, if not (logs can also be files), return the parent directory. If you need to process the actual file system, rather than parse the actual string.

Is there any standard feature?

+6
source share
5 answers

This can help

 var result = System.IO.Directory.Exists(m_logsDir) ? m_logsDir: System.IO.Path.GetDirectoryName(m_logsDir); 
+3
source
 new DirectoryInfo(m_logsDir).Name; 
+5
source

To do this, we have a piece of code line by line:

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

or

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

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

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

Your output will be what Logs supposed to be. However, if you do this:

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

Your output will be My Program , which causes a difference in output. I would either try to ensure the ending \ , otherwise you can do something like this:

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

Hope this helps.

0
source

According to the previous answer, you can use a slash as follows:

Path.GetDirectoryName(m_logsDir + "\");

Horrible, but it seems to work - is there a 0 or 1 slash at the end. The double slash is treated as a single slash of GetDirectoryName.

0
source

All Articles