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);
}
>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.