Write Rows from DataTable to Text File

When you try to print out a DataRow like that, it is calling Object.ToString(), which simply prints out the name of the type. What you want to do is something like:

sw.WriteLine(String.Join(",", row.ItemArray));

This will print a comma separated list of all of the items in the DataRow.


The below code will let you to write text file each column separated by '|'

    foreach (DataRow row in dt.Rows)
      {  
         object[] array = row.ItemArray;
         for (int i = 0; i < array.Length - 1; i++)
         {
           swExtLogFile.Write(array[i].ToString() + " | ");
         }
          swExtLogFile.WriteLine(array[array.Length - 1].ToString());             
     }

Reference link


Something like:

sw.WriteLine(row["columnname"].ToString());

would be more appropriate.

Tags:

C#

Datatable