user576510 user576510 - 1 year ago 59
ASP.NET (C#) Question

after email deleting attachment file, error "The process cannot access the file because it is being used by another process."

I am doing an email form. Email has attachments and after attaching files email is sent. Next there is requirement to delete file from server. When I tried to get the file it gave me the subject error. I am even calling GC.Collect() before deleting the file but error is still there. My code for deleting file is:

private void DeleteFiles(DataTable dt)
String[] sAttachments = new String[dt.Rows.Count];

sAttachments = new String[dt.Rows.Count];
for (Int32 J = 0; J < dt.Rows.Count; J++)
sAttachments[J] = dt.Rows[J]["AttachmentExt"].ToString().Trim();
string workDir = Server.MapPath(".") + @"\upload\";
if (File.Exists(workDir + sAttachments[J]))
File.Delete(workDir + sAttachments[J]);
catch (Exception ex)


For attaching file to email my code is:

oMess.Subject = sSubject;
string workDir = System.Web.HttpContext.Current.Server.MapPath(".") + @"\upload\";
if (Attachments != null)
for (Int32 I = 0; I < Attachments.Length; I++)
oatt = new Attachment(workDir+ sAttachments[I]);
oMess.IsBodyHtml = IsHtml;
oMess.Body = sBody;

Edit: My mail sending code is:

private void SendMessageGmail(MailMessage message)
SmtpClient client = new SmtpClient("");
client.EnableSsl = true;
client.UseDefaultCredentials = false;
NetworkCredential loginInfo = new NetworkCredential("myid", "mypassword");
client.Credentials = loginInfo;
client.Port = 587;

Plz guide and help. thanks

Answer Source

You should try to do oatt.Dispose();

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download