C#:删除文件时拒绝访问

时间:2013-10-01 13:28:47

标签: c#

我有一个c#应用程序来合并多个TIFF文件。合并文件后,我将其保存到其他位置,并删除原始TIFF(图像文件)。但它给出了错误"The process cannot access the file 'D:\A\Merged.tif' because it is being used by another process."

我也使用GC.collect()方法来释放资源......

请帮忙,如何删除这些文件?

 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;
    }

2 个答案:

答案 0 :(得分:2)

尽可能使用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);
         }
      }
   }
}

答案 1 :(得分:1)

您可能没有正确关闭图像文件。这可能是获得此异常的原因。请尝试以下代码

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++;
    }
}