Imaging.Heif icon indicating copy to clipboard operation
Imaging.Heif copied to clipboard

File handle not closed/disposed if exception is thrown

Open swingnchad opened this issue 2 years ago • 0 comments

If I pass an invalid or corrupt heic file to the HeifImage constructor, an exception is thrown without closing the file. If I try to delete the file I get an access violation exception.

            try
            {                
                using (var img = new HeifImage(heicImageFile)) // HeifException thrown here: "Heif image exception - Invalid input: No 'ftyp' box"
                using (var primary = img.PrimaryImage())
                {
                    primary.Write(jpegImageFile, 100);
                }

                File.Delete(heicImageFile);                
            }
            catch (Exception ex)
            {
                File.Delete(heicImageFile); // IOException thrown here: "The process cannot access the file xxx.heic because it is being used by another process."
            }

I would suggest you close/dispose the file handle in the finally block of a try/catch/finally so there are no memory leaks or file handles left open from an exception.

swingnchad avatar Apr 21 '23 20:04 swingnchad