I am trying to write byte array to a file and sending it as email. After that I need to delete the file from the saved location.
But while deleting, it throws the error
‘The process cannot access the file ‘file path’ because it is being
used by another process.’
As per the File.WriteAllBytes()
documentation, it Creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is overwritten. Pls help me to find a solution.
string FolderPath = MyPath + "PaySlips";
string filePath = FolderPath + "/" + userID + "-PaySlip_" + ddlMonth.SelectedItem.Text + "_" + ddlYear.SelectedItem.Text + ".pdf";
if (!Directory.Exists(FolderPath))
{
Directory.CreateDirectory(FolderPath);
}
File.WriteAllBytes(filePath, bytes);
ArrayList attachments = new ArrayList();
attachments.Add(filePath);
SendEmail(emailID, cc, attachments);
if (File.Exists(attachments[0].ToString())) {
File.Delete(attachments[0].ToString()); //exception happens here
}
”’
3
Answers
I got the solution. Thanks @Cleptus File.WriteAllBytes() is already closed and in the SendMail(), it's got opened again. So by disposing those objects, it worked
The SendEmail() method in my code has
I added dispose of SMTPClient and MailMessage in finally block
you need to delete the file after "close" not before. As long as the close has not executed, the file will be in the stream loop and it counts as its own process and thus cannot be deleted until the file is closed. Hope this helps. Im guessing your close statement is below that code. Move it before the delete statment.
string FolderPath = MyPath + "PaySlips";
string filePath = FolderPath + "/" + userID + "-PaySlip_" + ddlMonth.SelectedItem.Text + "_" + ddlYear.SelectedItem.Text + ".pdf";