Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

deleting a file in c# after sending email attachment

Tags:

c#

I have the following code that basically attaches a file to an email message then after all attachments are attached and email is sent, i try to delete all files, however I get a file in use exception. I believe the error comes in this line

Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);

I tried using this code but I get an cannot sent email message

using Attachment data = new Attachment(file, MediaTypeNames.Application.Octet)){
//and the rest of the code in here.

}


foreach (KeyValuePair<string, string> kvp in reports) {
    browser.GoTo(kvp.Value);
    Thread.Sleep(1000);

    System.IO.File.Move(@"C:\Reports\bidata.csv", @"C:\Reports\"+kvp.Key.ToString()+".csv");

    string file = @"C:\Reports\" + kvp.Key.ToString() + ".csv";

    Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);

    // Add time stamp information for the file.
    ContentDisposition disposition = data.ContentDisposition;
    disposition.CreationDate = System.IO.File.GetCreationTime(file);
    disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
    disposition.ReadDate = System.IO.File.GetLastAccessTime(file);
    // Add the file attachment to this e-mail message.

    mail.Attachments.Add(data);  
}

smtpserver.Send(mail);
string[] files = Directory.GetFiles(@"C:\Reports");
foreach (string files1 in files)
{
    File.Delete(files1);
}
like image 854
user541597 Avatar asked Oct 25 '12 18:10

user541597


2 Answers

In order to delete the files first you will have to dispose the attachment and mail objects and then delete the files

like image 123
HatSoft Avatar answered Sep 30 '22 16:09

HatSoft


Dispose the smtpclient by putting it in a usings or calling dispose directly. That should free the file resource and allow you to nuke it.

like image 33
Frobzig Avatar answered Sep 30 '22 14:09

Frobzig