I am creating a file in local drive with content by using below code.
File.WriteAllLines(path, contents);
I am attaching this file to a mail and sending acrross the team. Once mail sent I need to delete the file, to delete the file I am using below code but I am getting runtime error
File.Delete(path);
Error Message : The process cannot access the file, because it is being used by another process
by default WriteAllLines() method closes the file but still it is opened by another process. I can only delete the file by executing the code after sometime but this is not the scenario. I need to delete it once the mail has been sent.
Update
System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage();
mailMessage.To.Add(new System.Net.Mail.MailAddress(recipient, ToName));
mailMessage.From = new System.Net.Mail.MailAddress(From, FromName);
mailMessage.Subject = Subject; // "Outlook calendar as attachment"; // modified by Srikanth J on 28/06/2012
mailMessage.Body = "This is a test message";
System.Net.WebClient webclient = new System.Net.WebClient();
webclient.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
for (int i = 0; i < item.Attachments.Count; i++)
{
string url = item.Attachments.UrlPrefix + item.Attachments[i];
SPFile file = item.ParentList.ParentWeb.GetFile(url);
mailMessage.Attachments.Add(new System.Net.Mail.Attachment(file.OpenBinaryStream(), file.Name));
}
System.Net.Mail.Attachment mailAttachment = new System.Net.Mail.Attachment(path);
mailMessage.Attachments.Add(mailAttachment);
smtp.Send(mailMessage);
Any help is appriciated, Thank you.
MailMessageimplementsIDisposable, so you should be using theusingkeyword to release any resources when you’re done with it. If you don’t do that, yes, it’s very well possible that the file remains in use until the garbage collector happens to notice that you’re not using the message anymore.You could also call
Disposefor the attachment directly, but disposing of a message will already ensure all subobjects, including attachments, get disposed correctly.