-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathCSVReader.cs
More file actions
643 lines (581 loc) · 23.7 KB
/
Copy pathCSVReader.cs
File metadata and controls
643 lines (581 loc) · 23.7 KB
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
/*
* 2006 - 2018 Ted Spence, http://tedspence.com
* License: http://www.apache.org/licenses/LICENSE-2.0
* Home page: https://github.com/tspence/csharp-csv-reader
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Data;
using System.Reflection;
using System.ComponentModel;
using System.Text;
#if HAS_ASYNC
using System.Threading;
#endif
// These suggestions from Resharper apply because we don't want it to recommend fixing things needed for Net20:
// ReSharper disable LoopCanBeConvertedToQuery
// ReSharper disable ConvertIfStatementToNullCoalescingAssignment
// ReSharper disable ReplaceSubstringWithRangeIndexer
// ReSharper disable InvertIf
// ReSharper disable ConvertIfStatementToNullCoalescingExpression
namespace CSVFile
{
/// <summary>
/// Keeps track of which columns are excluded from CSV serialization / deserialization
/// </summary>
public class ExcludedColumnHelper
{
/// <summary>
/// Note that Dot Net Framework 2.0 does not support HashSet, but it does support Dictionary.
/// </summary>
private readonly Dictionary<string, int> _excluded;
private readonly CSVSettings _settings;
/// <summary>
/// Construct a helper object to track which columns are excluded from serialization
/// </summary>
/// <param name="settings"></param>
public ExcludedColumnHelper(CSVSettings settings)
{
if (settings?.ExcludedColumns == null || settings.ExcludedColumns.Length == 0)
{
_excluded = null;
}
else
{
_settings = settings;
_excluded = new Dictionary<string, int>();
foreach (var name in _settings.ExcludedColumns)
{
var excludedColumnName = name;
if (!_settings.HeadersCaseSensitive)
{
excludedColumnName = excludedColumnName.ToUpperInvariant();
}
_excluded.Add(excludedColumnName, 1);
}
}
}
/// <summary>
/// True if this column should be excluded
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public bool IsExcluded(string name)
{
if (_excluded == null) return false;
var excludedColumnName = name;
if (!_settings.HeadersCaseSensitive)
{
excludedColumnName = excludedColumnName.ToUpperInvariant();
}
return _excluded.ContainsKey(excludedColumnName);
}
}
/// <summary>
/// A helper object to deserialize a class based on CSV strings
/// </summary>
public class DeserializationHelper<T> where T : class, new()
{
private readonly int _numColumns;
private readonly Type[] _columnTypes;
private readonly TypeConverter[] _converters;
private readonly PropertyInfo[] _properties;
private readonly FieldInfo[] _fields;
private readonly MethodInfo[] _methods;
/// <summary>
/// Construct a new deserialization helper for a specific class containing all the information necessary
/// for optimized deserialization
/// </summary>
/// <param name="settings"></param>
/// <param name="headers"></param>
public DeserializationHelper(CSVSettings settings, string[] headers)
{
var settings1 = settings;
if (settings1 == null)
{
settings1 = CSVSettings.TSV;
}
if (headers == null) throw new Exception("CSV must have headers to be deserialized");
var return_type = typeof(T);
_numColumns = headers.Length;
// Set binding flags correctly
var bindings = BindingFlags.Public | BindingFlags.Instance;
if (!settings1.HeadersCaseSensitive)
{
bindings |= BindingFlags.IgnoreCase;
}
// Set up the list of excluded columns
var excluded = new ExcludedColumnHelper(settings1);
// Determine how to handle each column in the file - check properties, fields, and methods
_columnTypes = new Type[_numColumns];
_converters = new TypeConverter[_numColumns];
_properties = new PropertyInfo[_numColumns];
_fields = new FieldInfo[_numColumns];
_methods = new MethodInfo[_numColumns];
for (var i = 0; i < _numColumns; i++)
{
// Is this column excluded?
if (excluded.IsExcluded(headers[i])) continue;
// Check if this is a property
_properties[i] = return_type.GetProperty(headers[i], bindings);
if (_properties[i] != null && !_properties[i].CanWrite)
{
if (settings1.IgnoreReadOnlyProperties && settings1.IgnoreHeaderErrors)
{
_properties[i] = null;
continue;
}
throw new Exception($"The column header '{headers[i]}' matches a read-only property. To ignore this exception, enable IgnoreReadOnlyProperties and IgnoreHeaderErrors.");
}
// If we failed to get a property handler, let's try a field handler
if (_properties[i] == null)
{
_fields[i] = return_type.GetField(headers[i], bindings);
// If we failed to get a field handler, let's try a method
if (_fields[i] == null)
{
// Methods must be treated differently - we have to ensure that the method has a single parameter
var mi = return_type.GetMethod(headers[i], bindings);
if (mi != null)
{
if (mi.GetParameters().Length == 1)
{
_methods[i] = mi;
_columnTypes[i] = mi.GetParameters()[0].ParameterType;
}
else if (!settings1.IgnoreHeaderErrors)
{
throw new Exception(
$"The column header '{headers[i]}' matched a method with more than one parameter.");
}
}
else if (!settings1.IgnoreHeaderErrors)
{
throw new Exception(
$"The column header '{headers[i]}' was not found in the class '{return_type.FullName}'.");
}
}
else
{
_columnTypes[i] = _fields[i].FieldType;
}
}
else
{
_columnTypes[i] = _properties[i].PropertyType;
}
if (_columnTypes[i] != null)
{
_converters[i] = TypeDescriptor.GetConverter(_columnTypes[i]);
if (_converters[i] == null && !settings1.IgnoreHeaderErrors)
{
throw new Exception(
$"The column {headers[i]} (type {_columnTypes[i]}) does not have a type converter.");
}
}
}
}
/// <summary>
/// Deserialize a single row using precomputed converters
/// </summary>
/// <param name="line"></param>
/// <param name="row_num"></param>
/// <param name="settings"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public T Deserialize(string[] line, int row_num, CSVSettings settings)
{
// If this line is completely empty, do our settings permit us to ignore the empty line?
if (line.Length == 0 || (line.Length == 1 && line[0] == string.Empty) && settings.IgnoreEmptyLineForDeserialization)
{
return null;
}
// Does this line match the length of the first line? Does the caller want us to complain?
if (line.Length != _numColumns && !settings.IgnoreHeaderErrors)
{
throw new Exception($"Line #{row_num} contains {line.Length} columns; expected {_numColumns}");
}
// Construct a new object and execute each column on it
var obj = new T();
for (var i = 0; i < Math.Min(line.Length, _numColumns); i++)
{
if (_converters[i] == null) continue;
// Attempt to convert this to the specified type
object value = null;
if (settings.AllowNull && (line[i] == null || line[i] == settings.NullToken))
{
value = null;
}
else if (_converters[i].IsValid(line[i]))
{
value = _converters[i].ConvertFromString(line[i]);
}
else if (!settings.IgnoreHeaderErrors)
{
throw new Exception(
$"The value '{line[i]}' cannot be converted to the type {_columnTypes[i]}.");
}
// Can we set this value to the object as a property?
if (_properties[i] != null)
{
_properties[i].SetValue(obj, value, null);
}
else if (_fields[i] != null)
{
_fields[i].SetValue(obj, value);
}
else if (_methods[i] != null)
{
_methods[i].Invoke(obj, new object[] { value });
}
}
return obj;
}
}
/// <summary>
/// A reader that reads from a stream and emits CSV records
/// </summary>
#if HAS_ASYNC_IENUM
public class CSVReader : IAsyncEnumerable<string[]>, IEnumerable<string[]>, IDisposable
#else
public class CSVReader : IEnumerable<string[]>, IDisposable
#endif
{
private readonly CSVSettings _settings;
private readonly StreamReader _stream;
/// <summary>
/// The settings currently in use by this reader
/// </summary>
public CSVSettings Settings
{
get { return _settings; }
}
/// <summary>
/// If the first row in the file is a header row, this will be populated
/// </summary>
public string[] Headers { get; private set; }
/// <summary>
/// Convenience function to read from a string
/// </summary>
/// <param name="source">The string to read</param>
/// <param name="settings">The CSV settings to use for this reader (Default: CSV)</param>
/// <returns></returns>
public static CSVReader FromString(string source, CSVSettings settings = null)
{
if (settings == null)
{
settings = CSVSettings.CSV;
}
var byteArray = settings.Encoding.GetBytes(source);
var stream = new MemoryStream(byteArray);
return new CSVReader(stream, settings);
}
/// <summary>
/// Convenience function to read from a file on disk
/// </summary>
/// <param name="filename">The file to read</param>
/// <param name="settings">The CSV settings to use for this reader (Default: CSV)</param>
/// <param name="encoding">The string encoding to use for the reader (Default: UTF8)</param>
/// <returns></returns>
public static CSVReader FromFile(string filename, CSVSettings settings = null, Encoding encoding = null)
{
if (encoding == null)
{
encoding = Encoding.UTF8;
}
var sr = new StreamReader(filename, encoding);
return new CSVReader(sr, settings);
}
/// <summary>
/// Construct a new CSV reader off a streamed source
/// </summary>
/// <param name="source">The stream source. Note that when disposed, the CSV Reader will dispose the stream reader.</param>
/// <param name="settings">The CSV settings to use for this reader (Default: CSV)</param>
public CSVReader(StreamReader source, CSVSettings settings = null)
{
_stream = source;
_settings = settings;
if (_settings == null)
{
_settings = CSVSettings.CSV;
}
// Do we need to parse headers?
if (_settings.HeaderRowIncluded)
{
var line = source.ReadLine();
if (line != null && _settings.AllowSepLine)
{
var newDelimiter = CSV.ParseSepLine(line);
if (newDelimiter != null)
{
// We don't want to change the original settings, since they may be a singleton
_settings = _settings.CloneWithNewDelimiter(newDelimiter.Value);
line = source.ReadLine();
}
}
#if NET2_0 || NET4_0 || NET4_5
Headers = CSV.ParseLine(line, _settings) ?? new string[] {};
#else
Headers = CSV.ParseLine(line, _settings) ?? Array.Empty<string>();
#endif
}
else
{
Headers = _settings.AssumedHeaders;
}
}
/// <summary>
/// Construct a new CSV reader off a streamed source
/// </summary>
/// <param name="source">The stream source. Note that when disposed, the CSV Reader will dispose the stream reader.</param>
/// <param name="settings">The CSV settings to use for this reader (Default: CSV)</param>
public CSVReader(Stream source, CSVSettings settings = null)
{
_settings = settings;
if (_settings == null)
{
_settings = CSVSettings.CSV;
}
_stream = new StreamReader(source, _settings.Encoding);
// Do we need to parse headers?
if (_settings.HeaderRowIncluded)
{
var line = _stream.ReadLine();
if (line != null && _settings.AllowSepLine)
{
var newDelimiter = CSV.ParseSepLine(line);
if (newDelimiter != null)
{
// We don't want to change the original settings, since they may be a singleton
_settings = _settings.CloneWithNewDelimiter(newDelimiter.Value);
line = _stream.ReadLine();
}
}
#if NET2_0 || NET4_0 || NET4_5
Headers = CSV.ParseLine(line, _settings) ?? new string[] {};
#else
Headers = CSV.ParseLine(line, _settings) ?? Array.Empty<string>();
#endif
}
else
{
Headers = _settings.AssumedHeaders;
}
}
/// <summary>
/// Iterate through all lines in this CSV file
/// </summary>
/// <returns>An array of all data columns in the line</returns>
public IEnumerable<string[]> Lines()
{
return CSV.ParseStream(_stream, _settings);
}
/// <summary>
/// Iterate through all lines in this CSV file
/// </summary>
/// <returns></returns>
public IEnumerator<string[]> GetEnumerator()
{
return CSV.ParseStream(_stream, _settings).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#if HAS_ASYNC_IENUM
/// <summary>
/// Iterate through all lines in this CSV file using async
/// </summary>
/// <returns>An array of all data columns in the line</returns>
public IAsyncEnumerable<string[]> LinesAsync()
{
return CSV.ParseStreamAsync(_stream, _settings);
}
/// <summary>
/// Iterate through all lines in this CSV file using async
/// </summary>
/// <returns>An array of all data columns in the line</returns>
public IAsyncEnumerator<string[]> GetAsyncEnumerator(CancellationToken cancellationToken = new CancellationToken())
{
return CSV.ParseStreamAsync(_stream, _settings).GetAsyncEnumerator(cancellationToken);
}
/// <summary>
/// Deserialize the CSV reader into a generic list
/// </summary>
/// <typeparam name="T">The type of data to deserialize</typeparam>
/// <returns>A streaming collection of records from the CSV source</returns>
/// <exception cref="Exception">If the CSV source cannot be parsed into the type, throws exceptions</exception>
public async IAsyncEnumerable<T> DeserializeAsync<T>() where T : class, new()
{
var helper = new DeserializationHelper<T>(_settings, Headers);
// Alright, let's retrieve CSV lines and parse each one!
var row_num = 0;
await foreach (var line in this)
{
row_num++;
var obj = helper.Deserialize(line, row_num, _settings);
if (obj != null)
{
yield return obj;
}
}
}
#endif
/// <summary>
/// Read this file into a data table in memory
/// </summary>
/// <returns></returns>
public DataTable ReadAsDataTable()
{
var dt = new DataTable();
string[] firstLine = null;
// File contains column names - so name each column properly
if (Headers == null)
{
var rawLine = _stream.ReadLine();
firstLine = CSV.ParseLine(rawLine, _settings);
var list = new List<string>();
for (var i = 0; i < firstLine.Length; i++)
{
list.Add($"Column{i}");
}
this.Headers = list.ToArray();
}
// Add headers
var numColumns = Headers.Length;
foreach (var t in Headers)
{
dt.Columns.Add(new DataColumn(t, typeof(string)));
}
// If we had to read the first line to get dimensions, add it
var row_num = 1;
if (firstLine != null)
{
dt.Rows.Add(firstLine);
row_num++;
}
// Start reading through the file
foreach (var line in CSV.ParseStream(_stream, _settings))
{
// Does this line match the length of the first line?
if (line.Length != numColumns)
{
if (!_settings.IgnoreDimensionErrors)
{
throw new Exception($"Line #{row_num} contains {line.Length} columns; expected {numColumns}");
}
else
{
// Add as best we can - construct a new line and make it fit
var list = new List<string>();
list.AddRange(line);
while (list.Count < numColumns)
{
list.Add("");
}
dt.Rows.Add(list.GetRange(0, numColumns).ToArray());
}
}
else
{
dt.Rows.Add(line);
}
// Keep track of where we are in the file
row_num++;
}
// Here's your data table
return dt;
}
/// <summary>
/// Deserialize the CSV reader into a generic list
/// </summary>
/// <typeparam name="T">The type to deserialize</typeparam>
/// <returns>A streaming collection of objects as they are read from the source</returns>
/// <exception cref="Exception">If the CSV formatting does not match the object, throw errors</exception>
public IEnumerable<T> Deserialize<T>() where T : class, new()
{
var helper = new DeserializationHelper<T>(_settings, Headers);
// Alright, let's retrieve CSV lines and parse each one!
var row_num = 0;
foreach (var line in this)
{
row_num++;
var obj = helper.Deserialize(line, row_num, _settings);
if (obj != null)
{
yield return obj;
}
}
}
/// <summary>
/// Close our resources - specifically, the stream reader
/// </summary>
public void Dispose()
{
_stream.Dispose();
}
/// <summary>
/// Take a CSV file and chop it into multiple chunks of a specified maximum size.
/// </summary>
/// <param name="filename">The input filename to chop</param>
/// <param name="out_folder">The folder where the chopped CSV will be saved</param>
/// <param name="maxLinesPerFile">The maximum number of lines to put into each file</param>
/// <param name="settings">The CSV settings to use when chopping this file into chunks (Default: CSV)</param>
/// <returns>Number of files chopped</returns>
public static int ChopFile(string filename, string out_folder, int maxLinesPerFile, CSVSettings settings = null)
{
// Default settings
if (settings == null) settings = CSVSettings.CSV;
// Let's begin parsing
var file_id = 1;
var line_count = 0;
var file_prefix = Path.GetFileNameWithoutExtension(filename);
var ext = Path.GetExtension(filename);
CSVWriter cw = null;
StreamWriter sw = null;
// Read in lines from the file
using (var sr = new StreamReader(filename))
{
using (var cr = new CSVReader(sr, settings))
{
// Okay, let's do the real work
foreach (var line in cr.Lines())
{
// Do we need to create a file for writing?
if (cw == null)
{
var fn = Path.Combine(out_folder, file_prefix + file_id.ToString() + ext);
var fs = new FileStream(fn, FileMode.CreateNew);
sw = new StreamWriter(fs, settings.Encoding);
cw = new CSVWriter(sw, settings);
if (settings.HeaderRowIncluded)
{
cw.WriteLine(cr.Headers);
}
}
// Write one line
cw.WriteLine(line);
// Count lines - close the file if done
line_count++;
if (line_count >= maxLinesPerFile)
{
cw.Dispose();
cw = null;
file_id++;
line_count = 0;
}
}
}
}
// Ensure the final CSVWriter is closed properly
if (cw != null)
{
cw.Dispose();
cw = null;
}
return file_id;
}
}
}