Friday 23 October 2015

The process cannot access the file, because it is being used by another process C#

There was a scenario where i was creating a PDF file and sending to those to a mail. Creation of file and sending was fine with the code but the runtime error occurred when i was deleting same file after sending mail. I was assuming that there was something related with File IO flush, dispose and close. But nothing was related with them, the main problem was  into initialization of MailMessage Object. I changed my code and that worked for me, thus i solved the issue the process cannot access the file, because it is being used by another process.

Here is my sample code

   

//MailMessage msg = new MailMessage();//wrong
using (var mailMessage = new MailMessage())//right
{
...
}