Note
In the following code examples - for easier readability - exception handling has been omitted.
public static CsvWriter OpenWrite(
string filePath,
IReadOnlyCollection<string?> columnNames,
char delimiter = ',',
Encoding? textEncoding = null
)
Public Shared Function OpenWrite (
filePath As String,
columnNames As IReadOnlyCollection(Of String),
Optional delimiter As Char = ","C,
Optional textEncoding As Encoding = Nothing
) As CsvWriter
public:
static CsvWriter^ OpenWrite(
String^ filePath,
IReadOnlyCollection<String^>^ columnNames,
wchar_t delimiter = L',',
Encoding^ textEncoding = nullptr
)
static member OpenWrite :
filePath : string *
columnNames : IReadOnlyCollection<string> *
?delimiter : char *
?textEncoding : Encoding
(* Defaults:
let _delimiter = defaultArg delimiter ','
let _textEncoding = defaultArg textEncoding null
*)
-> CsvWriter
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.
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.
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,,
*/
ArgumentNullException | filePath is null. |
ArgumentException | filePath is not a valid file path - or - a column name in columnNames occurs twice. |
ArgumentOutOfRangeException | delimiter is either the double quotes " or a line break character ('\r' or '\n'). |
IOException | I/O error. |