CsvOpenWrite(String, IReadOnlyCollectionString, Char, Encoding) Method

Initializes a CsvWriter to write a CSV file with header row.

Definition

Namespace: FolkerKinzel.CsvTools
Assembly: FolkerKinzel.CsvTools (in FolkerKinzel.CsvTools.dll) Version: 2.0.2+e1e095fbd3614788c84dad3204b1e88c20f89802
C#
public static CsvWriter OpenWrite(
	string filePath,
	IReadOnlyCollection<string?> columnNames,
	char delimiter = ',',
	Encoding? textEncoding = null
)

Parameters

filePath  String
File path of the CSV file.
columnNames  IReadOnlyCollectionString

A collection of column names for the header to be written.

The collection determines the order in which the columns appear in the CSV file and their index in CsvRecord. The Record of the CsvWriter instance, which the method returns, can be accessed with this column names.

The collection will be copied. If the collection contains null values, empty strings or white space, these are replaced by automatically generated column names. Column names cannot appear twice. By default the comparison is case-sensitive but it will be reset to a case-insensitive comparison if the column names are also unique when treated case-insensitive.

delimiter  Char  (Optional)
The field separator character.
textEncoding  Encoding  (Optional)
The text encoding to be used or null for UTF8.

Return Value

CsvWriter
A CsvWriter instance that allows you to write data as a CSV file.

Remarks

If the target file already exists, it is truncated and overwritten.

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.
C#
using System.Text;
using FolkerKinzel.CsvTools;

namespace Examples;

internal static class CsvAnalyzerExample
{
    public static void ParseForeignCsvFile(string filePath)
    {
        const string nonStandardCsv = """


            First # "Second # Column"   
            1,"2",3 # "Get's
            too much" # LOST?

            too few


            """;

        File.WriteAllText(filePath, nonStandardCsv, Encoding.Unicode);

        using CsvReader csv = Csv.OpenReadAnalyzed(filePath);
        CsvRecord[] data = [.. csv];

        using (CsvWriter writer = Csv.OpenWrite(filePath, data[0].ColumnNames))
        {
            foreach (CsvRecord record in data)
            {
                writer.Record.FillWith(record.Values);
                writer.WriteRecord();
            }
        }

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

/*
 Console output:

Column1,Column2,Column3
First ,Second # Column,
"1,""2"",3 ","Get's
too much", LOST?
too few,,

*/

Exceptions

ArgumentNullExceptionfilePath is null.
ArgumentException

filePath is not a valid file path

- or -

a column name in columnNames occurs twice.

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

See Also