Search code examples
c#fileprocessfilehelpers

Unable to delete a file created by FileHelper assembly


I am fetching details from db and writing them on a file using FileHelper, attach the file as part of an email and try to delete the file after mail is sent.

 var engine = new FileHelperEngine<DataModel>();

 engine.WriteFile(filePath, data);

 //After Mail is sent, deleting the file.
 if (File.Exists(filePath))
 {                           
   File.Delete(filePath); //Error is thrown here
 }

Exception : The process cannot access the file '..//somefilepath' because it is being used by another process.

I have to delete these files as soon as the mail is sent , letting them reside on server will consume space in the server.

How to delete these files when held by another process?

EDIT: Thanks everyone for your response . The issue was occurring because of Attachment instance that was holding the file and was not letting me delete the file.

MailMessage mailobj= new MailMessage();
Attachment data = new Attachment(filePath);
mailobj.Attachments.Add(data);

//after sending mail, i disposed the data
 data.Dispose();

Solution

  • The problem is not coming from the code in the question. The WriteFile() function opens, writes, and closes the file automatically, so the file does not stay in use. The mail client is the culprit that is still using the file when you try to delete it. Make sure it finishes and releases the file before you try to delete it. If you need help with that, edit your question and add the code for sending the mail.

    Note: some mail clients can automatically delete the files after they successfully send it. Check if your mail client has that feature and enable it, so you don't need to delete the file by yourself.

    Also some mail clients accept memory streams. If your mail client accepts memory streams, you may consider saving your data to a MemoryStream and pass it to the mail client instead of a file. This way you don't need to worry about creating and deleting the file.