Writing a DataTable into a text file


This article help in Writing a DataTable into a text file . and I also learn the example code for Writing a DataTable into a text file

This Example method shows you how to write the content of the DataTable into a text file.
It uses C#.


// Method to write data to a file
// Input : a data table containing data and the file path
// Output : void



public void Write(DataTable dt, string filePath)
{
int i = 0;
StreamWriter sw = null;

try
{

sw = new StreamWriter(filePath, false);


for (i = 0; i < dt.Columns.Count - 1; i++)
{

sw.Write(dt.Columns[i].ColumnName + " | ");

}
sw.Write(dt.Columns[i].ColumnName);
sw.WriteLine();


foreach (DataRow row in dt.Rows)
{
object[] array = row.ItemArray;

for (i = 0; i < array.Length - 1; i++)
{
sw.Write(array[i].ToString() + “ | ");
}
sw.Write(array[i].ToString());
sw.WriteLine();

}

sw.Close();
}

catch (Exception ex)
{
MessageBox.Show("Invalid Operation : \n" + ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}




Comments



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: