John Louie Dela Cruz
John Louie Dela Cruz

Reputation: 669

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.

Upvotes: 2

Views: 4612

Answers (2)

Anonymous
Anonymous

Reputation: 1979

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

Upvotes: 4

Mihai Bratulescu
Mihai Bratulescu

Reputation: 1945

using(FileStream stream = new FileStream("thepath"))
{
      //do stuff with the file
      stream .Close();
}

Now the stream will be closed and disposed.

Upvotes: 1

Related Questions