Locked Preventing File Locking in E-mail Attachment

  • Friday, December 14, 2007 8:39 PM
     
     
    I'm attaching a file to an e-mail that I'm sending using the SmtpClient class (from System.Net.Mail). 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 use to attach the file to the e-mail:

    Code Block

    sHtmlConfirmation = "D:\\ftpsite\\from_web\\" + sFolder + "\\" + sFolder + ".htm";

    Attachment data = new Attachment (sHtmlConfirmation);
    Email.Attachments.Add (data);


    What do I need to include here to prevent Windows from locking the file when it uses it?

    Thanks.

    Johan Cyprich

All Replies

  • Friday, December 14, 2007 9:25 PM
     
     Answered

    The file is unlocked when the MailMessage object is disposed. THe easies method would be to use the using statement:

     

    Code Block

    using (MailMessage Email = new MailMessage("Johan@example.com", "Johan@example.com", "Test", "Test Message"))

    {

    string sHtmlConfirmation = "D:\\ftpsite\\from_web\\" + sFolder + "\\" + sFolder+ ".htm";

    Attachment data = new Attachment (sHtmlConfirmation);

    Email.Attachments.Add (data);

    SmtpClient client = new SmtpClient(server);

    client.Send(message);

    }

     

     

     

  • Friday, December 14, 2007 10:52 PM
     
     
    Thanks James. Your solution works perfectly. Smile
  • Friday, February 12, 2010 11:33 AM
     
     
    THX... NICE SOLUTION.


    Mujeeb