Monday, November 9, 2009

C# :Writing DataTable to a text file

Here goes the code to write a data table to a text file:

//Writing to a text file
int count = 0;
StreamWriter sw = null;
try
{
sw = new StreamWriter(@"C:\Users\asoory\Desktop\UniqueConsultantNames.txt", false);
for (count = 0; count < dtList.Columns.Count - 1; count++)
{
sw.Write(dtList.Columns[count].ColumnName + "");
}
sw.Write(dtList.Columns[count].ColumnName);
sw.WriteLine();
foreach (DataRow row in dtList.Rows)
{
object[] array = row.ItemArray;
for (count = 0; count < array.Length - 1; count++)
{
sw.Write(array[count].ToString() + "");
}
sw.Write(array[count].ToString());
sw.WriteLine();
}
sw.Close();
}
catch (Exception ex)
{
}

No comments: