进程无法访问文件文件名,因为它正在被另一个进程使用

本文关键字:进程 另一个 因为 访问 文件 文件名 | 更新日期: 2023-09-27 18:15:10

我正在用这个代码生成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文件时,某些句柄仍然打开。你应该在发送线程中删除它们