我正在使用此代码生成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);
}
我收到错误:
该过程无法访问文件' 00f。因为它正在 被另一个过程使用。
如何解决这个问题?这是因为在发送邮件时线程正在运行吗?
答案 0 :(得分:2)
当您尝试在主线程中删除它时,某些句柄仍然对pdf文件开放。您应该在发送主题中删除它们。