Note
In the following code examples - for easier readability - exception handling
has been omitted.
public static CsvReader OpenReadAnalyzed(
string filePath,
Encoding? defaultEncoding = null,
Header header = Header.ProbablyPresent,
bool disableCaching = false,
int analyzedLines = 5
)
Public Shared Function OpenReadAnalyzed (
filePath As String,
Optional defaultEncoding As Encoding = Nothing,
Optional header As Header = Header.ProbablyPresent,
Optional disableCaching As Boolean = false,
Optional analyzedLines As Integer = 5
) As CsvReader
public:
static CsvReader^ OpenReadAnalyzed(
String^ filePath,
Encoding^ defaultEncoding = nullptr,
Header header = Header::ProbablyPresent,
bool disableCaching = false,
int analyzedLines = 5
)
static member OpenReadAnalyzed :
filePath : string *
?defaultEncoding : Encoding *
?header : Header *
?disableCaching : bool *
?analyzedLines : int
(* Defaults:
let _defaultEncoding = defaultArg defaultEncoding null
let _header = defaultArg header Header.ProbablyPresent
let _disableCaching = defaultArg disableCaching false
let _analyzedLines = defaultArg analyzedLines 5
*)
-> CsvReader
The method performs a statistical analysis on the CSV file to find the appropriate parameters for reading the file. The result of the analysis is therefore always only an estimate, the accuracy of which increases with the number of lines analyzed. The analysis is time-consuming because the CSV file has to be accessed for reading.
The field delimiters COMMA (',', %x2C), SEMICOLON (';', %x3B), HASH ('#', %x23), TAB ('\t', %x09), and SPACE (' ', %x20) are recognized automatically.
This method also tries to determine the Encoding of the CSV file from the byte order mark (BOM). If no byte order mark can be found, defaultEncoding is used.
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. |
ArgumentOutOfRangeException | header is not a defined value of the Header enum. - or - header is a combination of Header values. |
ArgumentException | filePath is not a valid file path. |
IOException | I/O error. |