Exporting a DataTable to a CSV file

Hi

I was hoping their was a way I can use the ADO.net functionality to write the data contained in a DataTable object to a CSV file.

I’m quite new to C# development so I need a kick in the right direction.

Thanks

[814 byte] By [tinny4u] at [2007-12-18]
# 1

Have you tried the stream writer:

StreamWriter sw = new StreamWriter(@"C:\TestFile.Txt");

foreach (DataRow dr in dt.Rows)
{
sw.WriteLine("{0},{1},{2},{3}", dr[0], dr[1],dr[2].dr[3]);
}
sw.Close();
*****************************************************************************

PS I'm a beginner

Baldev at 2007-9-8 > top of Msdn Tech,.NET Development,.NET Framework Data Access and Storage...
# 2

Yep, thats basically what im doing in the mean time.

Im looking for away that i can get ADO.net to do it for me, in a similar way that you can use ADO to write out XML.

tinny4u at 2007-9-8 > top of Msdn Tech,.NET Development,.NET Framework Data Access and Storage...
# 3

Its all to do with your connection string.

With accessing CSV you need to thing of a folder as a non-relational database and the csv files in the folder as tables. Once you think like that you can understand how SQL statements with CSV files work. Here's a console application that demonstrates how to export CSV data.

Imports System.Data.OleDb

Imports System.IO

Module Module1

Sub Main()

Try

Dim conn As New OleDbConnection

conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" & _

"Data Source=C:\CSVFiles;Extended Properties=Text;"

conn.Open()

Dim cmd As New OleDbCommand

cmd.Connection = conn

cmd.CommandText = "CREATE TABLE afile.csv (Col1 string, Col2 string);"

cmd.ExecuteNonQuery()

cmd.CommandText = "INSERT INTO aFile.csv ([Col1], [Col2]) VALUES ('Hello', 'World');"

cmd.ExecuteNonQuery()

conn.Close()

Catch ex As Exception

Console.WriteLine(ex.Message)

End Try

Console.WriteLine("Complete. Press any key to exit.")

Console.ReadLine()

End Sub

End Module

DerekSmyth at 2007-9-8 > top of Msdn Tech,.NET Development,.NET Framework Data Access and Storage...

.NET Development

Site Classified