Path.GetDirectoryName [Ravi Krishnaswamy]

Clarifying the behavior of Path.GetDirectoryName.

 

This is a convenient string parsing method to get the directory path of a file path. It validates neither the given file path nor the returned directory path. This method merely removes the last element of the given file path, i.e. it returns a string consisting of all characters up to but not including the last backslash ("\") in the file path. The returned value is null if the file path is null or if the file path denotes a root (such as "\", "C:", or \\server\share).

 

Note: MSDN spec link below has a doc bug, it incorrectly states that "Calling this method with the path parameter set to "c:\" returns empty string" where as it actually returns null as I noted above.

 

From MSDN:

 

https://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemiopathclassgetdirectorynametopic.asp

 string fileName = @"C:\mydir\myfile.ext";
 string path = @"C:\mydir\";
 string rootPath = @"C:\";
 string directoryName;
     
 directoryName = Path.GetDirectoryName(fileName);
 Console.WriteLine("GetDirectoryName('{0}') returns '{1}'", 
     fileName, directoryName);
  
 directoryName = Path.GetDirectoryName(path);
 Console.WriteLine("GetDirectoryName('{0}') returns '{1}'", 
     path, directoryName);
  
 directoryName = Path.GetDirectoryName(rootPath);
 Console.WriteLine("GetDirectoryName('{0}') returns '{1}'", 
     rootPath, directoryName);
  

The sample code above should output:

GetDirectoryName('C:\mydir\myfile.ext') returns 'C:\mydir'

GetDirectoryName('C:\mydir\') returns 'C:\mydir'

GetDirectoryName('C:\') returns ''

 

Thanks

Ravi Krishnaswamy