Question

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.

Was it helpful?

Solution

Found the problem, and its not StreamWriter not closing itself after usings.

Chris Sinclair is right about DateTime not guaranteeing an unique file name. If your for-loop is short (therefore, fast), you can end up with duplicate names, which is what happened in my case.

For 5 emails, _txtName generated 5 identical file names, meaning I ended up with one file in the end since StreamWriter overwrites by default.

Also, I forgot to use x.Attachments.Dispose(); at the end of each loop. So when it re-iterated, x.Attachments.add() is still trying attach the same file (upload time) while StreamWriter begins to write to the same file cause _txtName generated duplicate names due to DateTime being slower than the for-loop.

TL;DR: The for-loop is too fast too furious.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top