2013-10-01 38 views
1

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

我也使用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; 
    } 
+1

你能告诉我们你是如何合并文件的吗?合并完成后您是否关闭文件? –

+1

直到你显示一些代码之前,你会一直对我的朋友低调。 –

+0

显示相关代码。做研究(即将你的例外信息粘贴到你喜欢的网页搜索引擎中)。请参阅例如[进程无法访问该文件,因为它正在被另一个进程使用](http://stackoverflow.com/questions/9006568/process-cannot-access-the-file-because-it-is-being-used逐另一处理)。 – CodeCaster

回答

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

我正在合并两个TIFF格式的文件而不是文本文件 –

+0

@HirenRaiyani这只是为了帮助。它不是实际的一段代码。 –

+0

对不起没有帮我.. –

2

你可能没有正确关闭图像文件读取文件的示例代码。这可能是得到这个异常的原因。尝试下面的代码

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

对不起,它的内存异常异常 –

+0

TIFF文件的大小是多少? – Muctadir

+0

文件大小是10到15 KB,但它也是一个大,但在这个例子中我使用10到15 kb的文件。 –