-1

Im using StreamWriter in a loop and on the first write attempt I am getting the "Cannot write to a closed TextWriter" error but the resource has just been opened so im not sure why this is, here is the code:-

 if(File.Exists(filename) == false)
                {
                    using (sw = new StreamWriter(File.Create(filename)));
                    {
                        for(int i =0; i < mfeTempLoserList.Count -1; i++)
                        {
                            sw.WriteLine(mfeTempLoserList[i]); //Error happening here on first loop
                        }
                    }   
                }
GKonheiser
  • 61
  • 1
  • 10

1 Answers1

0

OK so after a bit of asking around and research, I found the error was the semicolon at the end of the using statement. I removed it and now it works fine. Hope this helps someone. So it should look like this:-

if(File.Exists(filename) == false)
                {
                    using (sw = new StreamWriter(File.Create(filename))) // NO SEMICOLON HERE
                    {
                        for(int i =0; i < mfeTempLoserList.Count -1; i++)
                        {
                            sw.WriteLine(mfeTempLoserList[i]); //Error happening here on first loop
                        }
                    }   
                }
GKonheiser
  • 61
  • 1
  • 10