Path.GetDirectoryName [Ravi Krishnaswamy]

Path.GetDirectoryName [Ravi Krishnaswamy]

  • Comments 2

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:

 

http://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

 

  • You said "The returned value is null if the file path is null or if the file path denotes a root". This conflicts with the MSDN docs, which say it returns an empty string (not a null) if the path denotes a root. Could you clarify when it returns null and when it returns an empty string?
  • This is a bug in the MSDN doc. Thanks for reporting this.
Page 1 of 1 (2 items)