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.
如何解決此問題?發生這種情況是因爲在發送郵件時運行的線程?
你如何填充消息變量? 「smtp.Send(消息);」 – Viru
@Viru知道它將如何幫助解決問題? – Anup
好的。可能是我讀了你的代碼錯誤...我以爲你正在填充消息var與文件的內容,可能已經留下一些流在閱讀文件後打開,但無論如何再次讀你的代碼它是明確的消息是什麼,但一些內容作爲電子郵件而非文件內容的一部分 – Viru