Path.GetDirectoryName return value is case inconsistent

Written on

Following on from my last post about browser differences when using a FileUpload control, this post is documenting a small inconsitency I've found, only this time it appears to be with the .NET Framework itself, rather than different browsers using ASP.NET applications.

When you call Path.GetDirectoryName and pass in the path of a file, but for whatever reason your filename is in Windows tilde format, it may return a value with a different case than passing in the filename in full (i.e. without a tilde).

Let's say that you have a folder on the root of your hard drive called "FOLDER" (note that our folder name is in uppercase) and you have a file inside it called "filewithlongname.txt". The full path of that file is obviously "C:\FOLDER\filewithlongname.txt". Take a look at the following, but bear in mind that we'll pass in "C:\folder" (lowercase) as the file path, which is different in case to the real folder on our hard drive:

string dir1 = Path.GetDirectoryName("C:\\test\\Folder\\filewi~1.txt");
string dir2 = Path.GetDirectoryName("C:\\test\\Folder\\filewithlongname.txt");

These are the values you'll get:

// dir1: C:\test\FOLDER
// dir2: C:\test\Folder

So it appears that when you pass in the path of a file to the Path.GetDirectoryName method and your filename is in tilde format, the return value will be in the same case as it is on the hard drive, whereas if you don't use tilde format and instead pass the full name of the file in, it will return a value in the same case as what was passed in to it, regardless of whether that matches what's on the hard drive.