-
Notifications
You must be signed in to change notification settings - Fork 346
Expand file tree
/
Copy pathFileHelperEngine.cs
More file actions
717 lines (576 loc) · 23.3 KB
/
FileHelperEngine.cs
File metadata and controls
717 lines (576 loc) · 23.3 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
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Text;
using FileHelpers.Events;
#if ! MINI
#endif
namespace FileHelpers
{
/// <summary>
/// Basic engine to read record by record
/// </summary>
public class FileHelperEngine
: FileHelperEngine<object>
{
#region " Constructor "
/// <include file='FileHelperEngine.docs.xml' path='doc/FileHelperEngineCtr/*'/>
public FileHelperEngine(Type recordType)
: this(recordType, Encoding.Default)
{ }
/// <include file='FileHelperEngine.docs.xml' path='doc/FileHelperEngineCtr/*'/>
/// <param name="encoding">The Encoding used by the engine.</param>
public FileHelperEngine(Type recordType, Encoding encoding)
: base(recordType, encoding)
{
}
/// <include file='FileHelperEngine.docs.xml' path='doc/FileHelperEngineCtr/*'/>
/// <param name="ri">Record information on new type</param>
internal FileHelperEngine(RecordInfo ri)
: base(ri)
{
}
#endregion
}
/// <include file='FileHelperEngine.docs.xml' path='doc/FileHelperEngine/*'/>
/// <include file='Examples.xml' path='doc/examples/FileHelperEngine/*'/>
/// <typeparam name="T">The record type.</typeparam>
[DebuggerDisplay("FileHelperEngine for type: {RecordType.Name}. ErrorMode: {ErrorManager.ErrorMode.ToString()}. Encoding: {Encoding.EncodingName}")]
public class FileHelperEngine<T>
: EventEngineBase<T>,
IFileHelperEngine<T>
where T : class
{
private readonly bool mObjectEngine;
#region " Constructor "
/// <include file='FileHelperEngine.docs.xml' path='doc/FileHelperEngineCtr/*'/>
public FileHelperEngine()
: this(Encoding.Default)
{}
/// <include file='FileHelperEngine.docs.xml' path='doc/FileHelperEngineCtr/*'/>
/// <param name="encoding">The Encoding used by the engine.</param>
public FileHelperEngine(Encoding encoding)
: base(typeof(T), encoding)
{
mObjectEngine = typeof (T) == typeof (object);
}
/// <include file='FileHelperEngine.docs.xml' path='doc/FileHelperEngineCtr/*'/>
/// <param name="encoding">The Encoding used by the engine.</param>
/// <param name="recordType">Type of record we are reading</param>
protected FileHelperEngine(Type recordType, Encoding encoding)
: base(recordType, encoding)
{
mObjectEngine = typeof(T) == typeof(object);
}
/// <include file='FileHelperEngine.docs.xml' path='doc/FileHelperEngineCtr/*'/>
/// <param name="ri">Record information</param>
internal FileHelperEngine(RecordInfo ri)
: base(ri)
{
mObjectEngine = typeof(T) == typeof(object);
}
#endregion
#region " ReadFile "
/// <include file='FileHelperEngine.docs.xml' path='doc/ReadFile/*'/>
public T[] ReadFile(string fileName)
{
return ReadFile(fileName, int.MaxValue);
}
/// <include file='FileHelperEngine.docs.xml' path='doc/ReadFile/*'/>
/// <param name="maxRecords">The max number of records to read. Int32.MaxValue or -1 to read all records.</param>
public T[] ReadFile(string fileName, int maxRecords)
{
using (var fs = new InternalStreamReader(fileName, mEncoding, true, DefaultReadBufferSize))
{
T[] tempRes;
tempRes = ReadStream(fs, maxRecords);
fs.Close();
return tempRes;
}
}
/// <include file='FileHelperEngine.docs.xml' path='doc/ReadFile/*'/>
public List<T> ReadFileAsList(string fileName)
{
return ReadFileAsList(fileName, int.MaxValue);
}
/// <include file='FileHelperEngine.docs.xml' path='doc/ReadFile/*'/>
/// <param name="maxRecords">The max number of records to read. Int32.MaxValue or -1 to read all records.</param>
public List<T> ReadFileAsList(string fileName, int maxRecords)
{
using (var fs = new InternalStreamReader(fileName, mEncoding, true, DefaultReadBufferSize))
{
var res = ReadStreamAsList(fs, maxRecords);
fs.Close();
return res;
}
}
#endregion
#region " ReadStream "
/// <include file='FileHelperEngine.docs.xml' path='doc/ReadStream/*'/>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public T[] ReadStream(TextReader reader)
{
return ReadStream(reader, int.MaxValue);
}
/// <include file='FileHelperEngine.docs.xml' path='doc/ReadStream/*'/>
/// <param name="maxRecords">The max number of records to read. Int32.MaxValue or -1 to read all records.</param>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public T[] ReadStream(TextReader reader, int maxRecords)
{
var result = ReadStreamAsList(reader, maxRecords, null);
if (mObjectEngine)
{
return (T[])((ArrayList)result).ToArray(RecordInfo.RecordType);
}
else
return ((List<T>)result).ToArray();
}
private void ReadStream(TextReader reader, int maxRecords, DataTable dt)
{
ReadStreamAsList(reader, maxRecords, dt);
}
/// <include file='FileHelperEngine.docs.xml' path='doc/ReadStream/*'/>
/// <param name="maxRecords">The max number of records to read. Int32.MaxValue or -1 to read all records.</param>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public List<T> ReadStreamAsList(TextReader reader, int maxRecords)
{
var result = ReadStreamAsList(reader, maxRecords, null);
if (mObjectEngine)
{
var res = new List<T>(result.Count);
for (int i = 0; i < result.Count; i++)
{
res.Add((T) result[i]);
}
return res;
}
else
return (List<T>)result;
}
#if !MINI
private IList ReadStreamAsList(TextReader reader, int maxRecords, DataTable dt)
{
#endif
if (reader == null)
throw new ArgumentNullException("reader", "The reader of the Stream can´t be null");
var recordReader = new NewLineDelimitedRecordReader(reader);
ResetFields();
mHeaderText = String.Empty;
mFooterText = String.Empty;
IList result;
if (mObjectEngine)
result = new ArrayList();
else
result = new List<T>();
int currentRecord = 0;
var streamInfo = new StreamInfoProvider(reader);
using (var freader = new ForwardReader(recordReader, RecordInfo.IgnoreLast))
{
freader.DiscardForward = true;
string currentLine, completeLine;
mLineNumber = 1;
completeLine = freader.ReadNextLine();
currentLine = completeLine;
#if !MINI
if (MustNotifyProgress) // Avoid object creation
OnProgress(new ProgressEventArgs(0, -1, streamInfo.Position, streamInfo.TotalBytes));
#endif
if (RecordInfo.IgnoreFirst > 0)
{
for (int i = 0; i < RecordInfo.IgnoreFirst && currentLine != null; i++)
{
mHeaderText += currentLine + StringHelper.NewLine;
currentLine = freader.ReadNextLine();
mLineNumber++;
}
}
bool byPass = false;
if (maxRecords < 0)
maxRecords = int.MaxValue;
var line = new LineInfo(currentLine) {mReader = freader};
var values = new object[RecordInfo.FieldCount];
while (currentLine != null && currentRecord < maxRecords)
{
//Alireza Kousha 4/14/2011 : Fix Reported on: http://www.filehelpers.com/forums/viewtopic.php?f=4&t=1109 adding the following line:
completeLine = currentLine; // <------------------------------
try
{
mTotalRecords++;
currentRecord++;
line.ReLoad(currentLine);
var skip = false;
var record = (T)RecordInfo.Operations.CreateRecordHandler();
#if !MINI
if (MustNotifyProgress) // Avoid object creation
OnProgress(new ProgressEventArgs(currentRecord, -1, streamInfo.Position, streamInfo.TotalBytes));
BeforeReadEventArgs<T> e = null;
if (MustNotifyRead)
{
e = new BeforeReadEventArgs<T>(this, record, currentLine, LineNumber);
skip = OnBeforeReadRecord(e);
if (e.RecordLineChanged)
line.ReLoad(e.RecordLine);
}
#endif
if (skip == false)
{
if (RecordInfo.Operations.StringToRecord(record, line, values))
{
#if !MINI
if (MustNotifyRead) // Avoid object creation
skip = OnAfterReadRecord(currentLine, record, e.RecordLineChanged, LineNumber);
#endif
if (skip == false)
{
#if MINI
resArray.Add(record);
#else
if (dt == null)
result.Add(record);
else
dt.Rows.Add(RecordInfo.Operations.RecordToValues(record));
#endif
}
}
}
}
catch (Exception ex)
{
switch (mErrorManager.ErrorMode)
{
case ErrorMode.ThrowException:
byPass = true;
throw;
case ErrorMode.IgnoreAndContinue:
break;
case ErrorMode.SaveAndContinue:
var err = new ErrorInfo
{
mLineNumber = freader.LineNumber,
mExceptionInfo = ex,
mRecordString = completeLine,
// mColumnNumber = mColumnNum
};
mErrorManager.AddError(err);
break;
}
}
finally
{
if (byPass == false)
{
currentLine = freader.ReadNextLine();
mLineNumber++;
}
}
}
if (RecordInfo.IgnoreLast > 0)
{
mFooterText = freader.RemainingText;
}
}
return result;
}
#endregion
#region " ReadString "
/// <include file='FileHelperEngine.docs.xml' path='doc/ReadString/*'/>
public T[] ReadString(string source)
{
return ReadString(source, int.MaxValue);
}
/// <include file='FileHelperEngine.docs.xml' path='doc/ReadString/*'/>
/// <param name="maxRecords">The max number of records to read. Int32.MaxValue or -1 to read all records.</param>
public T[] ReadString(string source, int maxRecords)
{
if (source == null)
source = string.Empty;
using (var reader = new InternalStringReader(source))
{
var res = ReadStream(reader, maxRecords);
reader.Close();
return res;
}
}
/// <include file='FileHelperEngine.docs.xml' path='doc/ReadString/*'/>
public List<T> ReadStringAsList(string source)
{
return ReadStringAsList(source, int.MaxValue);
}
/// <include file='FileHelperEngine.docs.xml' path='doc/ReadString/*'/>
/// <param name="maxRecords">The max number of records to read. Int32.MaxValue or -1 to read all records.</param>
public List<T> ReadStringAsList(string source, int maxRecords)
{
if (source == null)
source = string.Empty;
using (var reader = new InternalStringReader(source))
{
var res = ReadStreamAsList(reader, maxRecords);
reader.Close();
return res;
}
}
#endregion
#region " WriteFile "
///// <include file='FileHelperEngine.docs.xml' path='doc/WriteFile/*'/>
//public void WriteFileWithHeader(string fileName, IEnumerable<T> records)
//{
// WriteFile(fileName, records, -1, true);
//}
///// <include file='FileHelperEngine.docs.xml' path='doc/WriteFile2/*'/>
//public void WriteFileWithHeader(string fileName, IEnumerable<T> records, int maxRecords)
//{
// WriteFile(fileName, records, maxRecords, true)
//}
/// <include file='FileHelperEngine.docs.xml' path='doc/WriteFile/*'/>
public void WriteFile(string fileName, IEnumerable<T> records)
{
WriteFile(fileName, records, -1);
}
///// <include file='FileHelperEngine.docs.xml' path='doc/WriteFile2/*'/>
//public void WriteFile(string fileName, IEnumerable<T> records, int maxRecords)
//{
// WriteFile(fileName, records, maxRecords, false);
//}
/// <include file='FileHelperEngine.docs.xml' path='doc/WriteFile2/*'/>
public void WriteFile(string fileName, IEnumerable<T> records, int maxRecords)
{
using (var fs = new StreamWriter(fileName, false, mEncoding, DefaultWriteBufferSize))
{
WriteStream(fs, records, maxRecords);
fs.Close();
}
}
#endregion
#region " WriteStream "
/// <include file='FileHelperEngine.docs.xml' path='doc/WriteStream/*'/>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public void WriteStream(TextWriter writer, IEnumerable<T> records)
{
WriteStream(writer, records, -1);
}
///// <include file='FileHelperEngine.docs.xml' path='doc/WriteStream/*'/>
//[EditorBrowsable(EditorBrowsableState.Advanced)]
//public void WriteStream(TextWriter writer, IEnumerable<T> records, int maxRecords)
//{
// WriteStream(writer, records, maxRecords);
//}
///// <include file='FileHelperEngine.docs.xml' path='doc/WriteStream/*'/>
//[EditorBrowsable(EditorBrowsableState.Advanced)]
//public void WriteStreamWithHeader(TextWriter writer, IEnumerable<T> records)
//{
// WriteStream(writer, records, -1, true);
//}
///// <include file='FileHelperEngine.docs.xml' path='doc/WriteStream/*'/>
//[EditorBrowsable(EditorBrowsableState.Advanced)]
//public void WriteStreamWithHeader(TextWriter writer, IEnumerable<T> records, int maxRecords)
//{
// WriteStream(writer, records, maxRecords, true);
//}
/// <include file='FileHelperEngine.docs.xml' path='doc/WriteStream2/*'/>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public void WriteStream(TextWriter writer, IEnumerable<T> records, int maxRecords)
{
if (writer == null)
throw new ArgumentNullException("writer", "The writer of the Stream can be null");
if (records == null)
throw new ArgumentNullException("records", "The records can be null. Try with an empty array.");
ResetFields();
if (!string.IsNullOrEmpty(mHeaderText))
if (mHeaderText.EndsWith (StringHelper.NewLine, StringComparison.Ordinal))
writer.Write(mHeaderText);
else
writer.WriteLine(mHeaderText);
string currentLine = null;
//ConstructorInfo constr = mType.GetConstructor(new Type[] {});
int max = maxRecords;
if (records is IList)
max = Math.Min(max < 0 ? int.MaxValue : max, ((IList)records).Count);
#if !MINI
if (MustNotifyProgress) // Avoid object creation
OnProgress(new ProgressEventArgs(0, max));
#endif
int recIndex = 0;
bool first = true;
foreach (var rec in records)
{
if (recIndex == maxRecords)
break;
mLineNumber++;
try
{
if (rec == null)
throw new BadUsageException(string.Format("The record at index {0} is null.", recIndex));
if (first)
{
first = false;
if (RecordInfo.RecordType.IsInstanceOfType(rec) == false)
throw new BadUsageException("This engine works with record of type " + RecordInfo.RecordType.Name + " and you use records of type " + rec.GetType().Name );
}
bool skip = false;
#if !MINI
if (MustNotifyProgress) // Avoid object creation
OnProgress(new ProgressEventArgs(recIndex + 1, max));
if (MustNotifyWrite)
skip = OnBeforeWriteRecord(rec, LineNumber);
#endif
if (skip == false)
{
currentLine = RecordInfo.Operations.RecordToString(rec);
#if !MINI
if (MustNotifyWrite)
currentLine = OnAfterWriteRecord(currentLine, rec);
#endif
writer.WriteLine(currentLine);
}
}
catch (Exception ex)
{
switch (mErrorManager.ErrorMode)
{
case ErrorMode.ThrowException:
throw;
case ErrorMode.IgnoreAndContinue:
break;
case ErrorMode.SaveAndContinue:
var err = new ErrorInfo
{
mLineNumber = mLineNumber,
mExceptionInfo = ex,
mRecordString = currentLine
};
// err.mColumnNumber = mColumnNum;
mErrorManager.AddError(err);
break;
}
}
recIndex++;
}
mTotalRecords = recIndex;
if (!string.IsNullOrEmpty(mFooterText))
if (mFooterText.EndsWith (StringHelper.NewLine, StringComparison.Ordinal))
writer.Write(mFooterText);
else
writer.WriteLine(mFooterText);
}
#endregion
#region " WriteString "
/// <include file='FileHelperEngine.docs.xml' path='doc/WriteString/*'/>
public string WriteString(IEnumerable<T> records)
{
return WriteString(records, -1);
}
/// <include file='FileHelperEngine.docs.xml' path='doc/WriteString2/*'/>
public string WriteString(IEnumerable<T> records, int maxRecords)
{
var sb = new StringBuilder();
using (var writer = new StringWriter(sb))
{
WriteStream(writer, records, maxRecords);
string res = writer.ToString();
return res;
}
}
#endregion
#region " AppendToFile "
/// <include file='FileHelperEngine.docs.xml' path='doc/AppendToFile1/*'/>
public void AppendToFile(string fileName, T record)
{
AppendToFile(fileName, new T[] {record});
}
/// <include file='FileHelperEngine.docs.xml' path='doc/AppendToFile2/*'/>
public void AppendToFile(string fileName, IEnumerable<T> records)
{
using (TextWriter writer = StreamHelper.CreateFileAppender(fileName, mEncoding, true, false, DefaultWriteBufferSize))
{
mHeaderText = String.Empty;
mFooterText = String.Empty;
WriteStream(writer, records);
writer.Close();
}
}
#endregion
#region " DataTable Ops "
#if ! MINI
/// <summary>
/// Read the records of the file and fill a DataTable with them
/// </summary>
/// <param name="fileName">The file name.</param>
/// <returns>The DataTable with the read records.</returns>
public DataTable ReadFileAsDT(string fileName)
{
return ReadFileAsDT(fileName, -1);
}
/// <summary>
/// Read the records of the file and fill a DataTable with them
/// </summary>
/// <param name="fileName">The file name.</param>
/// <param name="maxRecords">The max number of records to read. Int32.MaxValue or -1 to read all records.</param>
/// <returns>The DataTable with the read records.</returns>
public DataTable ReadFileAsDT(string fileName, int maxRecords)
{
using (var fs = new InternalStreamReader(fileName, mEncoding, true, DefaultReadBufferSize))
{
DataTable res;
res = ReadStreamAsDT(fs, maxRecords);
fs.Close();
return res;
}
}
/// <summary>
/// Read the records of a string and fill a DataTable with them.
/// </summary>
/// <param name="source">The source string with the records.</param>
/// <returns>The DataTable with the read records.</returns>
public DataTable ReadStringAsDT(string source)
{
return ReadStringAsDT(source, -1);
}
/// <summary>
/// Read the records of a string and fill a DataTable with them.
/// </summary>
/// <param name="source">The source string with the records.</param>
/// <param name="maxRecords">The max number of records to read. Int32.MaxValue or -1 to read all records.</param>
/// <returns>The DataTable with the read records.</returns>
public DataTable ReadStringAsDT(string source, int maxRecords)
{
if (source == null)
source = string.Empty;
using (var reader = new InternalStringReader(source))
{
DataTable res;
res = ReadStreamAsDT(reader, maxRecords);
reader.Close();
return res;
}
}
/// <summary>
/// Read the records of the stream and fill a DataTable with them
/// </summary>
/// <param name="reader">The stream with the source records.</param>
/// <returns>The DataTable with the read records.</returns>
public DataTable ReadStreamAsDT(TextReader reader)
{
return ReadStreamAsDT(reader, -1);
}
/// <summary>
/// Read the records of the stream and fill a DataTable with them
/// </summary>
/// <param name="reader">The stream with the source records.</param>
/// <param name="maxRecords">The max number of records to read. Int32.MaxValue or -1 to read all records.</param>
/// <returns>The DataTable with the read records.</returns>
public DataTable ReadStreamAsDT(TextReader reader, int maxRecords)
{
DataTable dt = RecordInfo.Operations.CreateEmptyDataTable();
dt.BeginLoadData();
ReadStream(reader, maxRecords, dt);
dt.EndLoadData();
return dt;
}
#endif
#endregion
}
}