Write Rows from DataTable to Text File

Viewed 75725
public void GenerateDetailFile()
{
  if (!Directory.Exists(AppVars.IntegrationFilesLocation))
  {
    Directory.CreateDirectory(AppVars.IntegrationFilesLocation);
  }

  DateTime DateTime = DateTime.Now;
  using (StreamWriter sw = File.CreateText(AppVars.IntegrationFilesLocation +
                                DateTime.ToString(DateFormat) + " Detail.txt"))
  {
    DataTable table = Database.GetDetailTXTFileData();

    foreach (DataRow row in table.Rows)
    {
      sw.WriteLine(row);
    }
  }
}

Not sure what I'm missing here but I think it might be the column name which I'm not sure how to set it up.

This is working fine, except, when it writes to the text file, it's writing this:

System.Data.DataRow
System.Data.DataRow
System.Data.DataRow
System.Data.DataRow
System.Data.DataRow
System.Data.DataRow
System.Data.DataRow
System.Data.DataRow
System.Data.DataRow
System.Data.DataRow

Can anyone give me a hand?

6 Answers

Try this:

To write the DataTable rows to text files in the specific directory

            var dir = @"D:\New folder\log";  // folder location

            if (!Directory.Exists(dir))  // if it doesn't exist, create
                Directory.CreateDirectory(dir);

            foreach (DataRow row in dt.Rows)
            {
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    result.Append(row[i].ToString());
                    result.Append(i == dt.Columns.Count - 1 ? "\n" : ",");
                }
                result.AppendLine();
            }
            string path = System.IO.Path.Combine(dir, "item.txt");
            StreamWriter objWriter = new StreamWriter(path, false);
            objWriter.WriteLine(result.ToString());
            objWriter.Close();
Related