-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCsvReader.cs
98 lines (82 loc) · 3.01 KB
/
CsvReader.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace Jannesen.FileFormat.Csv
{
public class CsvReader: IDisposable
{
private TextReader? _textReader;
private readonly CsvOptions _options;
private readonly StringBuilder _buf;
private int _rowIndex;
public CsvReader(TextReader textReader, CsvOptions options)
{
ArgumentNullException.ThrowIfNull(textReader);
ArgumentNullException.ThrowIfNull(options);
_textReader = textReader;
_options = options;
_rowIndex = 0;
_buf = new StringBuilder(256);
}
~CsvReader()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_textReader != null) {
_textReader.Dispose();
_textReader = null;
}
}
public CsvRow? ReadRow()
{
var colIndex = 0;
var cells = new List<CsvCell>();
ObjectDisposedException.ThrowIf(_textReader == null, this);
var c = _textReader.Read();
if (c < 0)
return null;
for (;;) {
_buf.Length = 0;
if (c == _options.StringQuote) {
for (;;) {
c = _textReader.Read();
if (c < 0)
throw new CsvException("EOF in quoted field.");
if (c == _options.StringQuote) {
c = _textReader.Read();
if (c != _options.StringQuote)
break;
}
_buf.Append((char)c);
}
}
else {
while (c >= 0 && c != _options.FieldSeperator && c != '\n' && c != '\r') {
_buf.Append((char)c);
c = _textReader.Read();
}
}
cells.Add(new CsvCell(_rowIndex, colIndex++, _buf.ToString(), _options));
if (c == _options.FieldSeperator) {
c = _textReader.Read();
continue;
}
if (c == '\r')
c = _textReader.Read();
if (c == '\n' || c < 0) {
++ _rowIndex;
return new CsvRow(cells.ToArray());
}
throw new CsvException("Invalid char in CSV document at row " +_rowIndex + ".");
}
}
}
}