Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7944065
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T00:27:06+00:00 2026-06-04T00:27:06+00:00

I’m creating PDF invoices in a C# MVC application that I’m attaching to an

  • 0

I’m creating PDF invoices in a C# MVC application that I’m attaching to an email and sending, ideally, once the email is sent I’d like to delete the invoice to free up server space and improve privacy/security. I’ve written code to do it but it fails 50% of the time because the file is locked by another process (I’m not sure if it’s the create/write process that’s locking it or the email send). I’m sending the email asynchronously (i.e. the code to delete doesn’t execute until the email has sent).

I’d appreciate some tips on how to handle this problem. I could run a job to clean up old files but I’d prefer to clean them up as I go…

I forgot to mention I am using iTextSharp to generate the PDF – the crux of it is this code is used to generate the final invoice (I am able to delete the list of files passed in as a param without drama):

/// <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();
            }
        }

The PDF File is then sitting on the server (e.g. “~/Invoices/0223.pdf”) ready to attach to an email like so:

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();

Then I attempt to delete it:

File.Delete(HttpContext.Current.Server.MapPath("/Invoices/" + invoiceId + ".pdf"));
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T00:27:07+00:00Added an answer on June 4, 2026 at 12:27 am

    Are you using a FileStream to open/read the file ?

    You could try to use a Stream that inherit from FileStream, and delete the file when the stream close:

    /// <summary>
    /// FileStream that automatically delete the file when closing
    /// </summary>
    public class AutoDeleteFileStream : FileStream
    {
        private string _fileName;
    
        public AutoDeleteFileStream(string fileName, FileMode fileMode, FileAccess fileAccess)
            : base(fileName, fileMode, fileAccess)
        {
            this._fileName = fileName;
        }
    
        public AutoDeleteFileStream(string fileName, FileMode fileMode)
            : base(fileName, fileMode)
        {
            this._fileName = fileName;
        }
    
        public override void Close()
        {
            base.Close();
            if (!string.IsNullOrEmpty(_fileName))
                File.Delete(_fileName);
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I've got a string that has curly quotes in it. I'd like to replace
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
For some reason, after submitting a string like this Jack’s Spindle from a text
I have a French site that I want to parse, but am running into
I am doing a simple coin flipping experiment for class that involves flipping a
I am trying to render a haml file in a javascript response like so:
I would like to run a str_replace or preg_replace which looks for certain words

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.