DataTableExtensionWriteCsv(DataTable, String, Char, IFormatProvider, Encoding, IEnumerableString, String) Method

Writes the content of the DataTable as a CSV file with header.

Definition

Namespace: FolkerKinzel.CsvTools
Assembly: FolkerKinzel.CsvTools (in FolkerKinzel.CsvTools.dll) Version: 2.0.1+2345335399184346d9b2cc992ed5c814406052c1
C#
public static void WriteCsv(
	this DataTable dataTable,
	string filePath,
	char delimiter = ',',
	IFormatProvider? formatProvider = null,
	Encoding? textEncoding = null,
	IEnumerable<string>? csvColumnNames = null,
	string? format = null
)

Parameters

dataTable  DataTable
The DataTable to save.
filePath  String
The file path of the CSV file to be written.
delimiter  Char  (Optional)
The field separator character.
formatProvider  IFormatProvider  (Optional)

The provider to use to format the value.

- or -

A null reference for InvariantCulture.

textEncoding  Encoding  (Optional)
The Encoding to be used or null for UTF8.
csvColumnNames  IEnumerableString  (Optional)

A collection of ColumnNames from dataTable that allows to select the DataColumns to export and to determine their order in the CSV file, or null to save the whole DataTable using its current column order.

Each item in this collection MUST be a ColumnName in dataTable.

format  String  (Optional)

A format String to use for all items that implement IFormattable.

- or -

A null reference to use the default format for each item.

Usage Note

In Visual Basic and C#, you can call this method as an instance method on any object of type DataTable. When you use instance method syntax to call this method, omit the first parameter. For more information, see Extension Methods (Visual Basic) or Extension Methods (C# Programming Guide).

Remarks

Creates a new CSV file. If the target file already exists, it is truncated and overwritten.

For serialization ToString(String, IFormatProvider) is used if the item implements IFormattable, otherwise ToString.

When exchanging CSV data with Excel, the appropriate arguments can be determined with GetExcelArguments.

Example

  Note

In the following code examples - for easier readability - exception handling has been omitted.

Simple DataTable serialization with CSV:

C#
using System.Data;
using System.Globalization;
using System.Text;
using FolkerKinzel.CsvTools;

namespace Examples;

internal static class DataTableExample
{
    internal static void SerializingDataTablesAsCsv(string filePath)
    {
        using var table = new DataTable();
        _ = table.Columns.Add("id", typeof(int));
        _ = table.Columns.Add("name", typeof(string));
        _ = table.Columns.Add("sales", typeof(decimal));
        _ = table.Columns.Add("last_purchase", typeof(DateOnly));
        _ = table.Columns.Add("reserved", typeof(string));

        _ = table.Rows.Add(1, "Susi", 4_711m, new DateOnly(2004, 3, 14), "my comment");
        _ = table.Rows.Add(2, "Tom", 38_527.28m, new DateOnly(2006, 12, 24));
        _ = table.Rows.Add(3, "Sören", 25.8m, new DateOnly(2011, 8, 27));

        string[] csvColumns = ["name", "last_purchase", "sales"];
        table.WriteCsv(filePath, csvColumnNames: csvColumns);

        Console.WriteLine(File.ReadAllText(filePath));


        // Write a CSV file that can be imported by Excel:
        Console.WriteLine();
        Console.WriteLine("Current culture: {0}", CultureInfo.CurrentCulture);
        Console.WriteLine();

        (char delimiter,
         IFormatProvider formatProvider,
         Encoding encoding) = Csv.GetExcelArguments();
        table.WriteCsv(filePath, delimiter, formatProvider, encoding, csvColumns);

        Console.WriteLine(File.ReadAllText(filePath, encoding));
    }
}

/*
Console output:

name,last_purchase,sales
Susi,03/14/2004,4711
Tom,12/24/2006,38527.28
Sören,08/27/2011,25.8

Current culture: de-DE

name;last_purchase;sales
Susi;14.03.2004;4711
Tom;24.12.2006;38527,28
Sören;27.08.2011;25,8
*/

Exceptions

ArgumentNullExceptiondataTable or filePath is null.
ArgumentException

filePath is not a valid file path.

- or -

csvColumnNames contains an item that is not a ColumnName in dataTable.

ArgumentOutOfRangeExceptiondelimiter is either the double quotes " or a line break character ('\r' or '\n').
IOExceptionI/O error.

See Also