簡體   English   中英

該進程無法訪問文件名,因為它正在被另一個進程使用

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM