Tuesday, May 3, 2016

Look for a file inside a directory in C#

We have seen how EnumerateFiles worked in our previous post and the differences between GetFiles too. So we will extend that method to find a file inside a directory with or without its extension. See the below method,
  private static string GetFileNameFromDirectory(string path, string fileName)  
   {  
     DirectoryInfo di = new DirectoryInfo(path);  
     if (di.Exists == false)  
       return string.Empty;  
     IEnumerable<string> dirs = (from file in di.EnumerateFiles(fileName)  
                   orderby file.LastWriteTime descending  
                   select file.Name).Distinct();  
     foreach (string Name in dirs)  
     {  
       if (Path.GetFileNameWithoutExtension(Name).ToLower() == (fileName).ToLower())  
         return Name;  
     }  
     dirs = (from file in di.EnumerateFiles(fileName + ".*")  
         orderby file.LastWriteTime descending  
         select file.Name).Distinct();  
     foreach (string Name in dirs)  
     {  
       if (Path.GetFileNameWithoutExtension(Name).ToLower() == (fileName).ToLower())  
         return Name;  
     }  
     int idx = fileName.LastIndexOf('.');  
     var flName = fileName.Substring(0, idx);  
     dirs = (from file in di.EnumerateFiles(flName + ".*")  
         orderby file.LastWriteTime descending  
         select file.Name).Distinct();  
     foreach (string Name in dirs)  
     {  
       if (Path.GetFileNameWithoutExtension(Name).ToLower() == (flName).ToLower())  
         return Name;  
     }  
     return string.Empty;  
   }  


Suppose you need to find whether the file exists on a particular directory or you need to find a file irrespective of it's extension, you can use this method.

"GetFileNameFromDirectory" expects two parameters.
Path : is the physical path to the folder
FileName : the name of the file you are looking for. Ex:  myImage.jpg or myImage.png or even you can just send myImage (without extension)

If a perfect match found, it will return the name of the file.
If there is no matching file with the extension you sent (myImage.jpg) it will look for a file similar to that name (myImage) without extension and return the matching file. (myImage.png)

Suppose you have more than one file with same name but different extensions, then it sorts the file based on LastWriteTime descending and pick the most recently added file to the directory. (Based on file attributes such as Last Modified Date.

Try this method and see how nice it works.

Happy Coding... :)

No comments:

Post a Comment