Preventing File Locking in E-mail Attachment

Posted by Johan Cyprich on 28 Jan 2008 | Tagged as: Programming

I’m trying to attach a file to an e-mail that I’m sending using the SmtpClient class (from System.Net.Mail) using C# for ASP.NET. Everything works correctly, but the problem is that the file that was uploaded gets locked in the folder by Windows and I can’t delete it afterwards.

This is the code I used to attach a file to an e-mail:

sHtmlConfirmation = "D:\\ftpsite\\from_web\\" + sFolder + "\\" + sFolder + ".htm";
Attachment data = new Attachment (sHtmlConfirmation);
Email.Attachments.Add (data);

I needed a solution to prevent Windows from locking a file that it uses, so I turned to the MSDN Forums for help. James Curran posted a working solution. He suggested employing the using statement to dispose the MailMessage object after the mail has been sent.

The code which fixes the problem is:

using (MailMessage Email = new MailMessage ())
{
// setup message details here
}

After the mail was sent, I was able to move the folder where the attached file was used.



Tweet This Tweet This Post!

Related posts:
    Preventing Deletions in Attached E-mail Files
    Extracting Attachments from E-mails
    How to Edit an Outlook 2010 E-mail
    The Dangers of Assumptions in Software Development

Share this post:

del.icio.us:Preventing File Locking in E-mail Attachment digg:Preventing File Locking in E-mail Attachment spurl:Preventing File Locking in E-mail Attachment wists:Preventing File Locking in E-mail Attachment simpy:Preventing File Locking in E-mail Attachment newsvine:Preventing File Locking in E-mail Attachment blinklist:Preventing File Locking in E-mail Attachment furl:Preventing File Locking in E-mail Attachment reddit:Preventing File Locking in E-mail Attachment fark:Preventing File Locking in E-mail Attachment blogmarks:Preventing File Locking in E-mail Attachment Y!:Preventing File Locking in E-mail Attachment smarking:Preventing File Locking in E-mail Attachment magnolia:Preventing File Locking in E-mail Attachment segnalo:Preventing File Locking in E-mail Attachment gifttagging:Preventing File Locking in E-mail Attachment

Follow Me:

Did you find this post interesting and useful? You can keep up to date on this blog by subscribing to my RSS feed, or you can have new posts sent to you by e-mail. You can also follow me on Twitter.


2 Responses to “Preventing File Locking in E-mail Attachment”

  1. on 19 Feb 2009 at 9:16 am 1.jose said …

    Thank you for your post :) I have not idea how to do what you need but made me think about how to do it now.

    Thanks!

    Jose

  2. on 21 Dec 2009 at 9:14 am 2.اخبار مصر said …

    I wasn’t aware of the many ripples and depth to this story until I surfed here through Google! Great job.
    .-= اخبار مصر´s last blog ..دار الأوبرا المصرية‏..‏الفارق بين فرقة أمريكية وبرودواي‏!! =-.

Trackback This Post | Subscribe to the comments through RSS Feed

Leave a Reply

CommentLuv badge