I have a program, every 30 seconds it writes its actions to a .txt file.
In backgroundWorker every 30 minutes, this file is sent to me by mail, but after sending it, when I try to write data, the error “this file is used in another stream” appears in the file. Please help solve the problem.

Here is the submission code:

 MailMessage mail = new MailMessage("От кого", "Кому","Заголовок", "Текст сообщения"); SmtpClient client = new SmtpClient("smtp.mail.ru"); client.Port = 587; System.Net.Mail.Attachment data = new System.Net.Mail.Attachment(nameDoc); // nameDoc - переменная содержащая путь к файлу client.Credentials = new System.Net.NetworkCredential("логин", "пароль"); client.EnableSsl = true; mail.Attachments.Add(data); client.Send(mail); 
  • How does the file write? - Grundy

1 answer 1

Attachment implements IDisposable , try to explicitly destroy it:

 MailMessage mail = new MailMessage("От кого", "Кому","Заголовок", "Текст сообщения"); SmtpClient client = new SmtpClient("smtp.mail.ru"); client.Port = 587; client.Credentials = new System.Net.NetworkCredential("логин", "пароль"); client.EnableSsl = true; using (System.Net.Mail.Attachment data = new System.Net.Mail.Attachment(nameDoc)) { mail.Attachments.Add(data); client.Send(mail); } 

And better destroy the entire MailMessage :

 SmtpClient client = new SmtpClient("smtp.mail.ru"); client.Port = 587; client.Credentials = new System.Net.NetworkCredential("логин", "пароль"); client.EnableSsl = true; using (var mail = new MailMessage("От кого", "Кому","Заголовок", "Текст сообщения")) { var data = new System.Net.Mail.Attachment(nameDoc)); mail.Attachments.Add(data); client.Send(mail); } 
  • Better then do Dispose for MailMessage. - Pavel Mayorov
  • @PavelMayorov yes, he looked - he destroys all attachments - PashaPash