Features
This code snippet is two functions that converts a DataTable to a CSV file. The One difference between the two functions is that the one with the Boolean parameter named headers allows you to signify that the first row in the CSV file contains header text.
References
The following namespaces/class will need to be added in order for the code to compile:
Code
Friend Sub ConvertDataTableToCSV(ByVal data As DataTable, ByVal path As String) Dim csv As String = String.Join(Environment.NewLine, (From row As DataRow In data.Rows.Cast(Of DataRow) Select String.Join(",", (From column As DataColumn In data.Columns.Cast(Of DataColumn) Select row.Item(column.ColumnName))))) IO.File.WriteAllText(path, csv) End Sub Friend Sub ConvertDataTableToCSV(ByVal data As DataTable, ByVal path As String, ByVal headers As Boolean) Dim csv As String = String.Empty If headers Then csv = String.Join((",", (From column As DataColumn In data.Columns.Cast(Of DataColumn) Select column.Caption).ToArray) & Environment.NewLine() End If csv &= String.Join(Environment.NewLine, (From row As DataRow In data.Rows.Cast(Of DataRow) Select String.Join(",", (From column As DataColumn In data.Columns.Cast(Of DataColumn) Select row.Item(column.ColumnName))))) IO.File.WriteAllText(path, csv) End Sub
Fiddle: https://dotnetfiddle.net/TOjUK3