Search code examples
c#.netjpeg

Changing the extension of multiple files to jpeg using C#


I am trying to change the extension of files within a folder to jpeg. I have used the below code to update the extension and it is working fine. But when i try to open each of the files, I am getting the error in photo viewer as "Windows photo viewer can't open this picture because the file appears to be damaged, corrupted or its too large."

 DirectoryInfo d = new DirectoryInfo(@"E:\New folder (2)");
                FileInfo[] Files = d.GetFiles(); 
                string str = "";
                foreach (FileInfo file in Files)
                {
                    str = str + ", " + file.Name;
                    string changed =  Path.ChangeExtension(file.FullName, ".jpg");
                    File.WriteAllText(changed, "Changed file");
                } 

Solution

  • JPEG files are not text files. You need to Read and write bytes instead. ie:

    DirectoryInfo d = new DirectoryInfo(@"E:\New folder (2)");
    FileInfo[] Files = d.GetFiles(); 
    
    foreach (FileInfo file in Files)
    {
       string changed =  Path.ChangeExtension(file.FullName, "jpg");
       File.Copy(file.FullName, changed);
    } 
    

    Of course file themselves should be JPEG for this to work.