/
CSVHelper.cs
220 lines (202 loc) · 8.19 KB
/
CSVHelper.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
[assembly: InternalsVisibleTo("Simple.UnitTests")]
namespace RafaelEstevam.Simple.Spider.Helper
{
/// <summary>
/// Helper to do stuff with CSV data
/// </summary>
public static class CSVHelper
{
/// <summary>
/// Split CSV lines using semicolon (rfc4180 standard)
/// </summary>
/// <param name="Lines">Lines to be splitted</param>
/// <returns>Enumeration of an array of strings</returns>
public static IEnumerable<string[]> CSVSplit(IEnumerable<string> Lines)
{
// rfc4180 standard
return DelimiterSplit(Lines, ';');
}
/// <summary>
/// Split CSV lines using specified delimiter
/// </summary>
/// <param name="Lines">Lines to be splitted</param>
/// <param name="delimiter">Specify which delimiter should be used</param>
/// <returns>Enumeration of an array of strings</returns>
public static IEnumerable<string[]> DelimiterSplit(IEnumerable<string> Lines, char delimiter)
{
foreach (var line in Lines)
{
yield return splitLine(line, delimiter).ToArray();
}
}
internal static IEnumerable<string> splitLine(string line, char delimiter)
{
bool isQuoted = false;
var sb = new StringBuilder();
// I will not implement escape now
foreach (var c in line)
{
if (c == '"')
{
// \/ Only start quoting at start
isQuoted = !isQuoted && sb.Length == 0;
continue;
}
if (!isQuoted && c == delimiter)
{
yield return sb.ToString();
sb.Clear();
continue;
}
sb.Append(c);
}
yield return sb.ToString();
}
/// <summary>
/// Splits a CSV file even if its compressed as .gz or .zip
/// </summary>
/// <param name="path">Path of the file</param>
/// <param name="encoding">Specify which encoding should be used</param>
/// <param name="delimiter">Specify which delimiter should be used</param>
/// <returns>Enumeration of an array of strings</returns>
public static IEnumerable<string[]> FileSplit(string path, Encoding encoding = null, char delimiter = ';')
{
return FileSplit(new FileInfo(path), encoding, delimiter);
}
/// <summary>
/// Splits a CSV file even if its compressed as .gz or .zip
/// </summary>
/// <param name="fi">File to be read</param>
/// <param name="encoding">Specify which encoding should be used</param>
/// <param name="delimiter">Specify which delimiter should be used</param>
/// <returns>Enumeration of an array of strings</returns>
public static IEnumerable<string[]> FileSplit(FileInfo fi, Encoding encoding = null, char delimiter = ';')
{
if (encoding == null) encoding = Encoding.Default;
using var fs = fi.OpenRead();
IEnumerable<string[]> items;
// choose the correct source
if (fi.Extension.Equals(".zip", StringComparison.InvariantCultureIgnoreCase))
items = zippedFileSpit(fs, encoding, delimiter);
else if (fi.Extension.Equals(".gz", StringComparison.InvariantCultureIgnoreCase))
items = compressedFileSpit(fs, encoding, delimiter);
else
items = FileSplit(new StreamReader(fs, encoding), delimiter);
// enumerate it
foreach (var i in items) yield return i;
// close after finished all items
fs.Close();
}
/// <summary>
/// Load DataRows from csv file
/// </summary>
/// <param name="path">Path of the file</param>
/// <param name="encoding">Specify which encoding should be used</param>
/// <param name="delimiter">Specify which delimiter should be used</param>
/// <param name="hasHeader">Defines if the first row is the header</param>
/// <returns></returns>
public static IEnumerable<DataRow> LoadRows(string path, Encoding encoding = null, char delimiter = ';', bool hasHeader = false)
{
DataTable dt = null;
foreach (var line in FileSplit(path, encoding, delimiter))
{
if (dt == null) // first
{
dt = new DataTable();
for (int i = 0; i < line.Length; i++)
{
dt.Columns.Add();
}
if (hasHeader)
{
// skip this line
continue;
}
}
var row = dt.NewRow();
row.ItemArray = line;
yield return row;
}
}
/// <summary>
/// Read a CSV file even if its compressed as .gz or .zip
/// </summary>
/// <param name="path">Path of the file</param>
/// <param name="encoding">Specify which encoding should be used</param>
/// <param name="delimiter">Specify which delimiter should be used</param>
/// <param name="hasHeader">Defines if the first row is the header</param>
/// <returns>A datatable with data</returns>
public static DataTable LoadFile(string path, Encoding encoding = null, char delimiter = ';', bool hasHeader = false)
{
return ToDataTable(FileSplit(path, encoding, delimiter), hasHeader);
}
private static IEnumerable<string[]> compressedFileSpit(FileStream fs, Encoding encoding, char delimiter)
{
var gz = new GZipStream(fs, CompressionMode.Decompress);
foreach (var v in FileSplit(new StreamReader(gz, encoding), delimiter))
{
yield return v;
}
}
private static IEnumerable<string[]> zippedFileSpit(FileStream fs, Encoding encoding, char delimiter)
{
var zip = new ZipArchive(fs, ZipArchiveMode.Read);
foreach (var entry in zip.Entries)
{
using var zipStream = entry.Open();
foreach (var v in FileSplit(new StreamReader(zipStream, encoding), delimiter))
{
yield return v;
}
}
}
/// <summary>
/// Splits lines from a stream
/// </summary>
/// <param name="streamReader">Stream to get lines from</param>
/// <param name="delimiter">Specify which delimiter should be used</param>
/// <returns>Enumeration of an array of strings</returns>
public static IEnumerable<string[]> FileSplit(StreamReader streamReader, char delimiter = ';')
{
string line;
while ((line = streamReader.ReadLine()) != null)
{
yield return splitLine(line, delimiter).ToArray();
}
}
/// <summary>
/// Exports the CSV result to a DataTable
/// </summary>
/// <param name="data">Data returned from other methods</param>
/// <param name="hasHeader">Defines if the first row is the header</param>
/// <returns>A datatable with data</returns>
public static DataTable ToDataTable(this IEnumerable<string[]> data, bool hasHeader = false)
{
DataTable dt = new DataTable();
var e = data.GetEnumerator(); // lets do it in steps ...
if (hasHeader)
{
if (e.MoveNext())
{
foreach (var c in e.Current)
{
dt.Columns.Add(c);
}
}
}
while (e.MoveNext())
{
dt.Rows.Add(e.Current);
}
return dt;
}
}
}