Introduction
When I started using the FileSystemWatcher class, I soon discovered that the file names it returns from its events are in lowercase rather than the case you would see in Windows Explorer e.g. filename.txt rather than FileName.txt. If you want to perform an action on the file such as moving the file, the file name in its new location will be in lowercase.
I searched around and found that other people also had the same issue, but I could not find a suitable solution. I came up with a solution where I use the Directory.GetFiles(directoryName, fileName) to return a FileInfo object with the correctly cased file name.
This is an example of an event handler for the FileSystemWatcher.Created event:
private void watcher_OnCreated(object source, FileSystemEventArgs e)
{
FileInfo file = new FileInfo(e.FullPath);
file = GetCorrectlyCasedFileInfo(file);
file.MoveTo(Path.Combine(@"C:\AnotherDirectory", file.Name));
}
The GetCorrectlyCasedFileInfo function takes the FileInfo object with the lowercase name and returns a FileInfo object with the correctly cased file name. There are a few checks to make sure the file exists (this shouldn't occur, but better to check than not), if it does not exist then the original FileInfo object is returned:
private FileInfo GetCorrectlyCasedFileInfo(FileInfo file)
{
if(Directory.Exists(file.DirectoryName))
{
string[] fileNames =
Directory.GetFiles(file.DirectoryName, file.Name);
if((fileNames.Length > 0)
&& (file.FullName.ToLower().Equals(fileNames[0].ToLower())))
{
file = new FileInfo(fileNames[0]);
}
}
return file;
}