Howto: Check the case sensitive existence of a file

Sometimes, especially for files running on external FTP servers, where file names are case sensitive, a file named myFILE.html, is not the same file as myfile.html in the same path!

This function, can be used on an NTFS path for that purpose where File.Exists would fail, because it is case insensitive. (However, it does not enable you to have two files with just a different case in the same path)

///


/// Checks existance of file using a case sensitive compare
///

/// must be full filename
///
static bool FileExists(string file)

{

string pathCheck = Path.GetDirectoryName(file);

string filePart = Path.GetFileName(file);

      if (string.IsNullOrEmpty(pathCheck))

      {

      throw new ArgumentException("The file must include a full path", file);

      }

      string[] checkFiles = Directory.GetFiles(pathCheck, filePart, SearchOption.TopDirectoryOnly);

      if (checkFiles != null && checkFiles.Length > 0)

      {

            //must be a binary compare

            return Path.GetFileName(checkFiles[0]) == filePart;

       }

       return false;

}

 

blog comments powered by Disqus