Log DataTable To CSV File
Appends the contents of a DataTable to a CSV file, optionally including headers and timestamps.
Each call appends data to the specified file. If IncludeHeaders is True , the column names are written as
the first line. If AddTimeStamp is enabled, a timestamp is included at the beginning of each row. Fields are written as plain strings without escaping for special characters (e.g., quotes or line breaks).
VB
Public Sub LogDataTableToCSVFile(ByVal SourceTable As Data.DataTable, LogFile As String,
Optional ByVal IncludeHeaders As Boolean = True, Optional Separator As String = ";",
Optional AddTimeStamp As Boolean = False)
Using sw As StreamWriter = File.AppendText(LogFile)
If (IncludeHeaders) Then
Dim headerValues As IEnumerable(Of String) = SourceTable.Columns.OfType(Of Data.DataColumn).Select(Function(column) column.ColumnName)
If AddTimeStamp Then
sw.WriteLine("TimeSTamp" + Separator + String.Join(Separator, headerValues))
Else
sw.WriteLine(String.Join(Separator, headerValues))
End If
End If
Dim items As IEnumerable(Of String) = Nothing
For Each row As Data.DataRow In SourceTable.Rows
items = row.ItemArray.Select(Function(obj) obj.ToString())
If AddTimeStamp Then
sw.WriteLine(CStr(Now) + Separator + String.Join(Separator, items))
Else
sw.WriteLine(String.Join(Separator, items))
End If
Next
sw.Flush()
End Using
End Sub