The process cannot access the file, because it is being used by another process
<p>I am creating a file in local drive with content by using below code. </p>

<pre><code>File.WriteAllLines(path, contents);
</code></pre>

<p>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</p>

<pre><code>File.Delete(path);
</code></pre>

<p><strong>Error Message</strong> : The process cannot access the file, because it is being used by another process</p>

<p>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. </p>

<p><strong>Update</strong></p>

<pre><code>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 &lt; 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);
</code></pre>

<p>Any help is appriciated, Thank you.</p>
