Note
In the following code examples - for easier readability - exception handling
has been omitted.
public static void SaveCsv(
this IEnumerable<IEnumerable<Object?>?> data,
string filePath,
char delimiter = ',',
IFormatProvider? formatProvider = null,
Encoding? textEncoding = null,
string? format = null
)
<ExtensionAttribute>
Public Shared Sub SaveCsv (
data As IEnumerable(Of IEnumerable(Of Object)),
filePath As String,
Optional delimiter As Char = ","C,
Optional formatProvider As IFormatProvider = Nothing,
Optional textEncoding As Encoding = Nothing,
Optional format As String = Nothing
)
public:
[ExtensionAttribute]
static void SaveCsv(
IEnumerable<IEnumerable<Object^>^>^ data,
String^ filePath,
wchar_t delimiter = L',',
IFormatProvider^ formatProvider = nullptr,
Encoding^ textEncoding = nullptr,
String^ format = nullptr
)
[<ExtensionAttribute>]
static member SaveCsv :
data : IEnumerable<IEnumerable<Object>> *
filePath : string *
?delimiter : char *
?formatProvider : IFormatProvider *
?textEncoding : Encoding *
?format : string
(* Defaults:
let _delimiter = defaultArg delimiter ','
let _formatProvider = defaultArg formatProvider null
let _textEncoding = defaultArg textEncoding null
let _format = defaultArg format null
*)
-> unit
The provider to use to format the value.
- or -
A null reference for InvariantCulture.
A format String to use for all items that implement IFormattable.
- or -
A null reference to use the default format for each item.
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.
using FolkerKinzel.CsvTools;
namespace Examples;
internal static class LinqOnCsvExample
{
public static void LinqOnCsv(string filePath)
{
object?[][] customers =
[
["Customer", "PhoneNumbers", "Sales"],
["Detlef", null, 3.85m],
["Susi", """
0177-4711,
123-4567
""", 39_457.26m],
["Gabi", "08-15", 28.70m]
];
customers.SaveCsv(filePath);
Console.WriteLine(File.ReadAllText(filePath));
using CsvReader csv = Csv.OpenRead(filePath);
Console.WriteLine();
Console.WriteLine("What phone numbers does Susi have?:");
Console.WriteLine(
csv.FirstOrDefault(x => x["Customer"].Span.Equals("Susi", StringComparison.Ordinal))?["PhoneNumbers"]);
}
}
/*
Console Output:
Customer,PhoneNumbers,Sales
Detlef,,3.85
Susi,"0177-4711,
123-4567",39457.26
Gabi,08-15,28.70
What phone numbers does Susi have?:
0177-4711,
123-4567
*/
ArgumentNullException | data or filePath is null. |
ArgumentException | filePath is not a valid file path. |
ArgumentOutOfRangeException | delimiter is either the double quotes " or a line break character ('\r' or '\n'). |
IOException | I/O error. |