At the 2nd iteration, the "file being used" error occurs at the "using (StreamWriter" line. Even though StreamWriter is supposed to auto-close itself after going out of the usings.
EDIT 1: Real Code
Note: mails is a List<MailMessage>
(instantiated with From/To addresses)
foreach (var x in mails)
{
x.Subject = "Updated Google Exchange Rates (" +
DateTime.Now.ToString(new CultureInfo("en-US")) +
")";
StringBuilder emailBody = new StringBuilder();
emailBody.AppendLine("abc"); //<-- simplified
x.Body = emailBody.ToString();
_txtName = x.Subject.Replace(...); //Replaces invalid file-name chars
//Note that _txtName will always be unique due to x.Subject's dependency on DateTime
using (StreamWriter sw = new StreamWriter("./Exchange Rate History/" + _txtName))
{
sw.WriteLine(emailBody);
sw.Close();
}
Attachment attachment = new Attachment("./Exchange Rate History/" + _txtName);
attachment.Name = _txtName;
x.Attachments.Add(attachment);
SmtpClient smtpClient = new SmtpClient("...")
{
Credentials = new System.Net.NetworkCredential("", ""),
Port = 25
};
smtpClient.Send(x);
smtpClient.Dispose();
}
I had to add "sw.Close();" At before the end of the "usings" for this loop to work. Why?
EDIT 2: Oh no! sw.Close() stopped working! "file being used" again.