关闭后立即从Web服务器删除文件的C#技术

Rob*_*Rob 1 c# asp.net-mvc itextsharp delete-file

我正在C#MVC应用程序中创建PDF发票,我附加到电子邮件并发送,理想情况下,一旦发送电子邮件,我想删除发票以释放服务器空间并提高隐私/安全性.我已编写代码来执行此操作,但它在50%的时间内失败,因为该文件被另一个进程锁定(我不确定是创建/写入进程是锁定它还是电子邮件发送).我正在异步发送电子邮件(即删除的代码在电子邮件发送之前不会执行).

我很欣赏一些如何处理这个问题的技巧.我可以找一份工作来清理旧文件,但我更愿意在我去的时候清理它们...

我忘了提到我正在使用iTextSharp生成PDF - 它的关键是这个代码用于生成最终发票(我能够删除作为参数传入的文件列表而不用戏剧):

/// <summary>
        /// http://stackoverflow.com/questions/4276019/itextsharp-pdfcopy-use-examples
        /// </summary>
        /// <param name="fileNames"></param>
        /// <param name="outFile"></param>
        private void CombineMultiplePDFs(List<string> files, string outFile)
        {
            int pageOffset = 0;
            int f = 0;

            iTextSharp.text.Document document = null;
            PdfCopy writer = null;

            foreach (string file in files)
            {
                // we create a reader for a certain document
                PdfReader reader = new PdfReader(file);
                reader.ConsolidateNamedDestinations();
                // we retrieve the total number of pages
                int n = reader.NumberOfPages;

                pageOffset += n;

                if (f == 0)
                {
                    // step 1: creation of a document-object
                    document = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(1));
                    // step 2: we create a writer that listens to the document
                    writer = new PdfCopy(document, new FileStream(outFile, FileMode.Create));
                    // step 3: we open the document
                    document.Open();
                }
                // step 4: we add content
                for (int i = 0; i < n; )
                {
                    ++i;
                    if (writer != null)
                    {
                        PdfImportedPage page = writer.GetImportedPage(reader, i);
                        writer.AddPage(page);
                    }
                }
                PRAcroForm form = reader.AcroForm;

                if (form != null && writer != null)
                {
                    writer.CopyAcroForm(reader);
                }

                f++;
            }

            // step 5: we close the document
            if (document != null)
            {
                document.Close();
            }
        }
Run Code Online (Sandbox Code Playgroud)

然后PDF文件就位于服务器上(例如"〜/ Invoices/0223.pdf"),准备附加到这样的电子邮件:

MailMessage mailMessage = new MailMessage();
        mailMessage.From = new MailAddress(WebConfig.GetWebConfigKey(AppSettingsKey.ReplyEmailAddress.ToString()));
        mailMessage.To.Add(new MailAddress(user.Email));
        mailMessage.Subject = emailTemplate.TemplateSubject;
        mailMessage.Body = emailTemplate.TemplateContent;
        mailMessage.IsBodyHtml = false;
        mailMessage.Attachments.Add(new Attachment(HttpContext.Current.Server.MapPath("/Invoices/" + invoiceId + ".pdf")));

        SmtpClient client = new SmtpClient();

        try
        {
            client.Send(mailMessage);
        }
        catch{...}{
            //Error handling
        }

        client.Dispose();
Run Code Online (Sandbox Code Playgroud)

然后我尝试删除它:

File.Delete(HttpContext.Current.Server.MapPath("/Invoices/" + invoiceId + ".pdf"));
Run Code Online (Sandbox Code Playgroud)

Thi*_*tes 6

而不是将文件保存到磁盘,并导致性能,IO和删除问题,请查看您的PDF和邮件库是否支持将PDF写入MemoryStream,并将该流附加到电子邮件中.