Free Support Forum -

Files not being released from stream (C# .NET)

Below is the code that I am running to combine multiple TIFF files. The problem that I am running into is that files remain locked, and the following exception is thrown:

The process cannot access the file ‘C:\temp\test\testTIFF\CombineTest2\AsposeCombined.tif’ because it is being used by another process.

I have all the filestreams within using statements, and all the filestreams are explicitly closed. The problem seems to be with the final save function because if I comment that part out, the iteration of the files and frames work fine. Is there something that I’m missing?

    public static void CombineImageFiles(string fpDest, string[] safp)
        if (safp == null || safp.GetLength(0) < 1)

        int nFirstFile = 0;
        bool bDone = false;
            if (!File.Exists(safp[nFirstFile]))
                bDone = true;

        } while (!bDone && nFirstFile < safp.Length);

        if (!bDone)

        using (FileStream fileStream1 = new FileStream(safp[0], FileMode.Open))
            using (TiffImage image1 = (TiffImage)Image.Load(fileStream1))
                for (int i = nFirstFile + 1; i < safp.Length; ++i)
                    string fp = safp[i];

                    if (!File.Exists(fp))

                    using (FileStream fileStream = new FileStream(fp, FileMode.Open))
                        using (TiffImage image = (TiffImage)Image.Load(fileStream))
                            int nPageCount = image.Frames.Length;
                            for (int p = 0; p < nPageCount; p++)
                                // Create an instance of TIffFrame and copy frame of source image
                                TiffFrame frame = TiffFrame.CopyFrame(image.Frames[p]);

                                // Add copied frame to destination image

                TiffOptions outputSettings = new TiffOptions(TiffExpectedFormat.Default);
                ResolutionSetting res = new ResolutionSetting(300, 300);  // 300 x 300 DPI    
                outputSettings.BitsPerSample = new ushort[] { 4 };
                outputSettings.Compression = TiffCompressions.Lzw;
                outputSettings.Photometric = TiffPhotometrics.Palette;
                outputSettings.Palette = ColorPaletteHelper.Create4BitGrayscale(false);
                outputSettings.ResolutionSettings = res;

                using (FileStream outputStream = new FileStream(fpDest, FileMode.Create, FileAccess.Write))

                    image1.Save(outputStream, outputSettings);

            // Save the image with changes            


I have observed the issue shared by you and have created an issue with ID IMAGINGNET-3750 as investigation in our issue tracking system. In the mean while, I suggest you to please try copying the FileStream to MemoryStrem in your application and use that. I hope this shall avoid the issue you are facing.