Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C#: System.ObjectDisposedException: 'Cannot write to a closed TextWriter.'

I’m writing a program that exports data from a DataTable into a csv file but when I run the program I get the error : System.ObjectDisposedException: ‘Cannot write to a closed TextWriter.’

Here’s the code:

 StreamWriter sw = new StreamWriter("CMS.csv", true);

            do
            {
                // Headers
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    sw.Write(dt.Columns[i]);
                    if (i < dt.Columns.Count - 1)
                    {
                        sw.Write(",");
                    }
                }
                sw.Write(sw.NewLine);

                // Rows
                foreach (DataRow dr in dt.Rows)
                {
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        if (!Convert.IsDBNull(dr[i]))
                        {
                            string value = dr[i].ToString();
                            if (value.Contains(','))
                            {
                                value = String.Format("\"{0}\"", value);
                                sw.Write(value);
                            }
                            else
                            {
                                sw.Write(dr[i].ToString());
                            }
                        }
                        if (i < dt.Columns.Count - 1)
                        {
                            sw.Write(",");
                        }
                    }
                    sw.Write(sw.NewLine);
                }

                sw.Close();
            } while (dt.Rows.Count != 0);
        }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You need to move the call to sw.Close(); to be outside of the do/while loop.

Better yet, recommend that you use ‘using’ instead.

using (StreamWriter sw = new StreamWriter("CMS.csv", true)) {
   ... the do/while loop
}

that way, using will always take care of closing the stream, even if an exception happens.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading