Search code examples
c#renametolower

How do I de-capitalize all file extensions given a directory?


    originalFiles = Directory.GetFiles(fbFolderBrowser.SelectedPath).Where(file => !file.EndsWith(".db")).ToArray();

foreach (string file in originalFiles)
    {
         File.Move(file, file.Replace(".JPG", ".jpg"));
         File.Move(file, file.Replace(".TIFF", ".tiff"));
         File.Move(file, file.Replace(".JPEG", ".jpeg"));
         File.Move(file, file.Replace(".BMP", ".bmp"));
         File.Move(file, file.Replace(".GIF", ".gif"));
    }

I thought running the above would change the file extensions to lower case.

I have files in the directory:

AAA_1.jpg
AAA_2.JPG
BBB_1.TIFF
BBB_2.GIF

I want it to to be:

AAA_1.jpg
AAA_2.jpg
BBB_1.tiff
BBB_2.gif

How would I go about doing this?


Solution

  • Use the ToLower() method of the String class, and the ChangeExtension() method of the Path class. This should allow you to lowercase all of the extensions without having to enumerate every possible extension.

    DirectoryInfo folder = new DirectoryInfo("c:\whatever");
    FileInfo[] files = dirInfo.GetFiles("*.*");
    
    
    foreach (var file in files)
    {
        File.Move(file.FullName, Path.ChangeExtension(file, 
           Path.GetExtension(file).ToLower()));     
    }