2015-09-30 33 views
1

我生成PDF文件与此代码:,因为它正由另一个进程使用该进程无法访问该文件的文件名

foreach (var emp in empList) 
{ 
    ....  
    Byte[] bytes; 
    using (var ms = new MemoryStream()) 
    { 

     //Create an iTextSharp Document which is an abstraction of a PDF but **NOT** a PDF 
     using (var doc = new Document()) 
     { 

      //Create a writer that's bound to our PDF abstraction and our stream 
      using (var writer = PdfWriter.GetInstance(doc, ms)) 
      { 
       //Open the document for writing 
       doc.Open(); 

       using (var htmlWorker = new iTextSharp.text.html.simpleparser.HTMLWorker(doc)) 
       { 

        //HTMLWorker doesn't read a string directly but instead needs a TextReader (which StringReader subclasses) 
        using (var sr = new StringReader(EmailBody)) 
        { 

         //Parse the HTML 
         htmlWorker.Parse(sr); 
        } 
       } 

       doc.Close(); 
      } 
     } 

     bytes = ms.ToArray(); 
    } 

    bool isexist = System.IO.Directory.Exists(Server.MapPath("~/" + Session["SchemaName"].ToString() + "/HRLetters")); 
    if (!isexist) 
    { 
     System.IO.Directory.CreateDirectory(Server.MapPath("~/" + Session["SchemaName"].ToString() + "/HRLetters")); 
    } 
    System.IO.File.WriteAllBytes(Server.MapPath("~/" + Session["SchemaName"].ToString() + "/HRLetters/" + emp.Code.ToString() + ".pdf"), bytes.ToArray()); 
} 

然后我把所有的PDF文件作为附件通过电子邮件与此代码:

....... 
SmtpClient smtp = new SmtpClient 
       { 
        Host = data.SMTPServer, // smtp server address here...      
        Port = data.PortNo, 
        EnableSsl = data.SSL, 
        DeliveryMethod = SmtpDeliveryMethod.Network, 
        Credentials = new System.Net.NetworkCredential(senderID, senderPassword), 
        Timeout = 30000, 
       }; 
       Thread th = new Thread(() => { smtp.Send(message); }); 
       th.Start(); 

然后最后我尝试将删除该文件夹:

if (System.IO.Directory.Exists(Server.MapPath("~/" + Session["SchemaName"].ToString()))) 
{ 
    System.IO.Directory.Delete(Server.MapPath("~/" + Session["SchemaName"].ToString()), true); 
} 

我得到的错误:

The process cannot access the file '001.pdf' because it is being used by another process.

如何解决此问题?发生这种情况是因为在发送邮件时运行的线程?

+0

你如何填充消息变量? “smtp.Send(消息);” – Viru

+0

@Viru知道它将如何帮助解决问题? – Anup

+0

好的。可能是我读了你的代码错误...我以为你正在填充消息var与文件的内容,可能已经留下一些流在阅读文件后打开,但无论如何再次读你的代码它是明确的消息是什么,但一些内容作为电子邮件而非文件内容的一部分 – Viru

回答

2

当您尝试在主线程中删除它时,某些句柄仍然对PDF文件开放。您应该在发送线程中删除它们

相关问题