C#: Why am I getting "the process cannot access the file * because it is being used by another proce

Posted by zxcvbnm on Stack Overflow See other posts from Stack Overflow or by zxcvbnm
Published on 2010-03-19T18:41:57Z Indexed on 2010/03/19 18:51 UTC
Read the original article Hit count: 256

Filed under:

I'm trying to convert bmp files in a folder to jpg, then delete the old files. The code works fine, except it can't delete the bmp's.

        DirectoryInfo di = new DirectoryInfo(args[0]);
        FileInfo[] files = di.GetFiles("*.bmp");
        foreach (FileInfo file in files)
        {
            string newFile = file.FullName.Replace("bmp", "jpg");
            Bitmap bm = (Bitmap)Image.FromFile(file.FullName);
            bm.Save(newFile, ImageFormat.Jpeg);
        }
        for (int i = 0; i < files.Length; i++)
            files[i].Delete();

The files aren't being used by another program/process like the error indicates, so I'm assuming the problem is here. But to me the code seems fine, since I'm doing everything sequentially. This is all that there is to the program too, so the error can't be caused by code elsewhere.

© Stack Overflow or respective owner

Related posts about c#