Search code examples
c#system.io.directory

Deleting files gives an error (The process cannot access the file..)


I'm currently debugging my code because it gives me an error:

The process cannot access the file because it is being used by another process.

And i think that the error occurs in this lines of code

foreach (var filename in filenames)
{
    var file = Path.Combine(filePath, filename);
    mail.Attachments.Add(new Attachment(file));
}

// Send Mail
smtpServer.Send(mail);

DeleteFiles();

I want to delete the files in the folder when the mail is sent using this method

private void DeleteFiles()
{
    string filePath = Server.MapPath("~/Content/attachments");
    Array.ForEach(Directory.GetFiles(filePath), System.IO.File.Delete);
}

I read about closing/disposing? FileStream and etc. but how can i use that in my code? Thanks in advance.


Solution

  • mail.dispose(); You should dispose mail before deleting the file. This should remove the lock on the file.

    foreach (var filename in filenames)
    {
        var file = Path.Combine(filePath, filename);
        mail.Attachments.Add(new Attachment(file));
    }
    
    // Send Mail
    smtpServer.Send(mail);
    mail.Dispose();
    DeleteFiles();
    

    https://msdn.microsoft.com/en-us/library/0w54a951(v=vs.110).aspx