diff --git a/.gitignore b/.gitignore index 3424c79..c37a718 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,4 @@ obj/ project.lock.json .DS_Store *.pyc +/.vs \ No newline at end of file diff --git a/CsvParser.cs b/CsvParser.cs index 7b77952..946fb0c 100644 --- a/CsvParser.cs +++ b/CsvParser.cs @@ -9,6 +9,8 @@ public class CsvParser { private CsvTable _table; private StreamReader _reader; + private static string _delimeter; + private const string DefaultDelimeter = ","; private CsvParser() { @@ -16,21 +18,31 @@ private CsvParser() public static CsvTable ParseTable(byte[] data, bool normalizeHeaderNames = true) { - return new CsvParser().InternalParse(data, normalizeHeaderNames); + _delimeter = DefaultDelimeter; + return new CsvParser().InternalParse(data, normalizeHeaderNames, _delimeter); } - private CsvTable InternalParse(byte[] data, bool normalizeHeaderNames) + public static CsvTable ParseTable(byte[] data, bool normalizeHeaderNames = true, string delimeter = DefaultDelimeter) { + _delimeter = delimeter; + return new CsvParser().InternalParse(data, normalizeHeaderNames, _delimeter); + } + + private CsvTable InternalParse(byte[] data, bool normalizeHeaderNames, string delimeter) + { + _delimeter = delimeter; _table = new CsvTable(); _reader = new StreamReader(new MemoryStream(data)); string[] row = null; ReadHeaders(normalizeHeaderNames); - for (;;) { + for (; ; ) + { row = GetLineValues(); - if (row == null) { + if (row == null) + { break; } @@ -45,9 +57,11 @@ private void ReadHeaders(bool normalizeHeaderNames) string[] line = GetLineValues(); int hIndex = 0; - foreach (var name in line) { + foreach (var name in line) + { string columnName = name; - if (normalizeHeaderNames) { + if (normalizeHeaderNames) + { columnName = new string(name.ToLower() .Where(c => char.IsLetterOrDigit(c)).ToArray()); } @@ -61,11 +75,12 @@ private string[] GetLineValues() string[] result; string line = _reader.ReadLine(); - if (line == null) { + if (line == null) + { return null; } - result = Regex.Split(line, @",(?=(?:[^""]*""[^""]*"")*(?![^""]*""))"); + result = Regex.Split(line, $@"{_delimeter}(?=(?:[^""]*""[^""]*"")*(?![^""]*""))"); return result; } diff --git a/README.md b/README.md index bf519b6..353be42 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,6 @@ # csvtools Csv parsing tools for dotnet core +Permits delimeters other than just ",". + NuGet package: https://www.nuget.org/packages/CsvToolsCore/1.0.0