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)
return;
int nFirstFile = 0;
bool bDone = false;
do
{
if (!File.Exists(safp[nFirstFile]))
nFirstFile++;
else
bDone = true;
} while (!bDone && nFirstFile < safp.Length);
if (!bDone)
return;
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))
continue;
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
image1.AddFrame(frame);
}
}
fileStream.Close();
}
}
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);
outputStream.Close();
}
}
// Save the image with changes
fileStream1.Close();
}
}