9using System.Collections.Generic;
10using System.ComponentModel;
13using System.Text.RegularExpressions;
14using System.Threading.Tasks;
29 encoding = encoding ?? Encoding.UTF8;
36 var data = File.ReadAllText(path, encoding);
37 return Parse(data, delimiter);
49 encoding = encoding ?? Encoding.UTF8;
56 using (var reader =
new StreamReader(path, encoding))
58 var data = await reader.ReadToEndAsync();
59 return Parse(data, delimiter);
65 var extension = Path.GetExtension(path);
66 if (extension.Equals(
".csv", StringComparison.OrdinalIgnoreCase))
71 if (extension.Equals(
".tsv", StringComparison.OrdinalIgnoreCase))
76 throw new Exception($
"Delimiter estimation failed. Unknown Extension: {extension}");
87 if (delimiter ==
Delimiter.Auto)
throw new InvalidEnumArgumentException(
"Delimiter estimation from string is not supported.");
88 return Parse(data, delimiter);
95 var sheet =
new List<List<string>>();
96 var row =
new List<string>();
97 var cell =
new StringBuilder();
98 var insideQuoteCell =
false;
101 var delimiterSpan = delimiter.ToChar().ToString().AsSpan();
102 var crlfSpan =
"\r\n".AsSpan();
103 var oneDoubleQuotSpan =
"\"".AsSpan();
104 var twoDoubleQuotSpan =
"\"\"".AsSpan();
106 while (start < data.Length)
108 var length = start <= data.Length - 2 ? 2 : 1;
109 var span = data.AsSpan(start, length);
111 if (span.StartsWith(delimiterSpan))
115 cell.Append(delimiter.ToChar());
124 else if (span.StartsWith(crlfSpan))
138 else if (span.StartsWith(twoDoubleQuotSpan))
143 else if (span.StartsWith(oneDoubleQuotSpan))
145 insideQuoteCell = !insideQuoteCell;
150 cell.Append(span[0]);
155 if (row.Count > 0 || cell.Length > 0)
164 static void AddCell(List<string> row, StringBuilder cell)
166 row.Add(cell.ToString());
170 static void AddRow(List<List<string>> sheet, ref List<string> row)
173 row =
new List<string>();
178 data = Regex.Replace(data,
@"\r\n|\r|\n",
"\r\n");
static void ConvertToCrlf(ref string data)
static void AddCell(List< string > row, StringBuilder cell)
static Delimiter EstimateDelimiter(string path)
static void AddRow(List< List< string > > sheet, ref List< string > row)
static List< List< string > > LoadFromString(string data, Delimiter delimiter=Delimiter.Comma)
Load CSV data from string.
static List< List< string > > LoadFromPath(string path, Delimiter delimiter=Delimiter.Auto, Encoding encoding=null)
Load CSV data from specified path.
static List< List< string > > Parse(string data, Delimiter delimiter)
static async Task< List< List< string > > > LoadFromPathAsync(string path, Delimiter delimiter=Delimiter.Auto, Encoding encoding=null)
Load CSV data asynchronously from specified path.