Tuesday, April 5, 2016

GetFileNameWithoutExtension in C#

No matter the extension, what if you need to find whether there is a file matching to a certain name in that particular directory? Look at the below peace of code,

 private static string GetFilePathFromDirectory(string path, string fileName)  
   {  
     DirectoryInfo di = new DirectoryInfo(path);  
     FileInfo[] smFiles = di.GetFiles();  
     foreach (FileInfo fi in di.GetFiles())  
     {  
       if (Path.GetFileNameWithoutExtension(fi.Name).ToLower() == (fileName).ToLower())  
         return fi.FullName;  
     }  
     return string.Empty;  
   }  

You can pass the folder path, and the file name without extension, if there is a matching file, it will return with the extension.

Copy it and try yourself,

Happy Coding...



No comments:

Post a Comment