-
Notifications
You must be signed in to change notification settings - Fork 2
/
CsvParser.cs
73 lines (58 loc) · 1.8 KB
/
CsvParser.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
namespace CsvTools
{
public class CsvParser
{
private CsvTable _table;
private StreamReader _reader;
private CsvParser()
{
}
public static CsvTable ParseTable(byte[] data, bool normalizeHeaderNames = true)
{
return new CsvParser().InternalParse(data, normalizeHeaderNames);
}
private CsvTable InternalParse(byte[] data, bool normalizeHeaderNames)
{
_table = new CsvTable();
_reader = new StreamReader(new MemoryStream(data));
string[] row = null;
ReadHeaders(normalizeHeaderNames);
for (;;) {
row = GetLineValues();
if (row == null) {
break;
}
_table.AddRow(row);
}
return _table;
}
private void ReadHeaders(bool normalizeHeaderNames)
{
string[] line = GetLineValues();
int hIndex = 0;
foreach (var name in line) {
string columnName = name;
if (normalizeHeaderNames) {
columnName = new string(name.ToLower()
.Where(c => char.IsLetterOrDigit(c)).ToArray());
}
var header = new CsvHeader(hIndex++, columnName);
_table.AddHeader(header);
}
}
private string[] GetLineValues()
{
string[] result;
string line = _reader.ReadLine();
if (line == null) {
return null;
}
result = Regex.Split(line, @",(?=(?:[^""]*""[^""]*"")*(?![^""]*""))");
return result;
}
}
}