Monday, January 5, 2009

Create a text file using Dataset or Datatable in C#

I am currently working with the Dataset. I had a requirement in which i have to write a functionality in which all the data is written to the text file. The requirement is like create a text file and all the columns will be separated by tilde symbol. Below is the sample code which will solve the problem.
void CreateTextfile(string FilePath,Datatable dt)
{
int i = 0;
StreamWriter swTextFile= null;
try
{
swTextFile= new StreamWriter(filePath, false);
for (i = 0; i < dt.Columns.Count - 1; i++)
{
swTextFile.Write(dt.Columns[i].ColumnName + " ");
}
swTextFile.Write(dt.Columns[i].ColumnName);
swTextFile.WriteLine();
foreach (DataRow row in dt.Rows)
{
object[] array = row.ItemArray;
for (i = 0; i < array.Length - 1; i++)
{
swTextFile.Write(array[i].ToString() + "~");
}
swTextFile.Write(array[i].ToString());
swTextFile.WriteLine();
}
swTextFile.Close();
}
catch (Exception ex)
{
throw ex;
}
}

No comments: