![](/img/trans.png)
[英]the process cannot access the file 'filename' because it is being used by another process. and Access to the path 'filename' is denied
[英]The process cannot access the file filename because it is being used by another process
我正在使用以下代码生成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);
}
我得到错误:
该进程无法访问文件001.pdf,因为该文件正在被另一个进程使用。
如何解决这个问题? 是否由于邮件发送时线程正在运行而发生?
当您尝试在主线程中删除pdf文件时,某些句柄仍然打开。 您应该在发送线程中将其删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.