[英]The process cannot access the file filename because it is being used by another process
I am generating PDFs with this Code: 我正在使用以下代码生成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());
}
Then I send all the PDF files as an attachment through mail with this Code: 然后,我使用以下代码通过邮件将所有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();
Then finally I try to the delete the folder: 然后最后我尝试删除该文件夹:
if (System.IO.Directory.Exists(Server.MapPath("~/" + Session["SchemaName"].ToString())))
{
System.IO.Directory.Delete(Server.MapPath("~/" + Session["SchemaName"].ToString()), true);
}
I get the Error: 我得到错误:
The process cannot access the file '001.pdf' because it is being used by another process.
该进程无法访问文件001.pdf,因为该文件正在被另一个进程使用。
How to solve this Issue? 如何解决这个问题? Is this happening because of the Thread running at the time of Mail send?
是否由于邮件发送时线程正在运行而发生?
Some handle is still open to the pdf file while you try to delete it in the main thread. 当您尝试在主线程中删除pdf文件时,某些句柄仍然打开。 You should delete them in the sending thread .
您应该在发送线程中将其删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.