I have ac# application to merge more than one TIFF file. After merging the files, i am saving it to some other location,and deleting the original TIFF(image file). But it's giving an error "The process cannot access the file 'D:\\A\\Merged.tif' because it is being used by another process."
i am also use GC.collect() method to free the resources...
Kindly help, How to delete such files?
int mergeTiffPages(string filepath,string[] path)
{
string[] sa = path;
ImageCodecInfo info = null;
foreach (ImageCodecInfo ice in ImageCodecInfo.GetImageEncoders())
if (ice.MimeType == "image/tiff")
info = ice;
Encoder enc = Encoder.SaveFlag;
EncoderParameters ep = new EncoderParameters(1);
ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.MultiFrame);
Bitmap pages = null;
int frame = 0;
foreach (string s in sa){
if (frame == 0){
pages = (Bitmap)Image.FromFile(s);
//save the first frame
pages.Save(filepath, info, ep);
}
else{
//save the intermediate frames
ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.FrameDimensionPage);
Bitmap bm = (Bitmap)Image.FromFile(s);
pages.SaveAdd(bm, ep);
}
if (frame == sa.Length - 1)
{
//flush and close.
ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.Flush);
pages.SaveAdd(ep);
}
frame++;
}
return 1;
}
Wrap your code with Using {}
Blocks if possible. Here is a sample code for reading files using Using
using System;
using System.IO;
class Test
{
static void Main() {
using (TextWriter w = File.CreateText("log.txt")) {
w.WriteLine("This is line one");
w.WriteLine("This is line two");
}
using (TextReader r = File.OpenText("log.txt")) {
string s;
while ((s = r.ReadLine()) != null) {
Console.WriteLine(s);
}
}
}
}
You are probably not closing image files properly. That might be the reason for getting this exception. Try code below
foreach (string s in sa){
if (string.IsNullOrEmpty(s))
{
continue;
}
using (FileStream fileStream = System.IO.File.Open(s, FileMode.Open))
{
if (frame == 0){
pages = (Bitmap)Image.FromStream(fileStream);
//save the first frame
}
else{
//save the intermediate frames
}
if (frame == sa.Length - 1)
{
//flush and close.
}
frame++;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.