-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Copy pathTextFieldParser.cs
1154 lines (1036 loc) · 38.4 KB
/
TextFieldParser.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
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
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
namespace Microsoft.Data.Analysis
{
internal enum FieldType
{
Delimited,
FixedWidth
}
internal class QuoteDelimitedFieldBuilder
{
private readonly StringBuilder _field;
private bool _fieldFinished;
private int _index;
private int _delimiterLength;
private readonly Regex _delimiterRegex;
private readonly string _spaceChars;
private bool _malformedLine;
public QuoteDelimitedFieldBuilder(Regex delimiterRegex, string spaceChars)
{
_delimiterRegex = delimiterRegex;
_spaceChars = spaceChars;
_field = new StringBuilder();
}
public bool FieldFinished => _fieldFinished;
public string Field => _field.ToString();
public int Index => _index;
public int DelimiterLength => _delimiterLength;
public bool MalformedLine => _malformedLine;
public void BuildField(string line, int startAt)
{
_index = startAt;
int length = line.Length;
while (_index < length)
{
if (line[_index] == '"')
{
// Are we at the end of a file?
if (_index + 1 == length)
{
// We've found the end of the field
_fieldFinished = true;
_delimiterLength = 1;
// Move index past end of line
_index++;
return;
}
// Check to see if this is an escaped quote
if (_index + 1 < line.Length && line[_index + 1] == '"')
{
_field.Append('"');
_index += 2;
continue;
}
// Find the next delimiter and make sure everything between the quote and delimiter is ignorable
int Limit;
Match delimiterMatch = _delimiterRegex.Match(line, _index + 1);
if (!delimiterMatch.Success)
{
Limit = length - 1;
}
else
{
Limit = delimiterMatch.Index - 1;
}
for (int i = _index + 1; i < Limit; i++)
{
if (_spaceChars.IndexOf(line[i]) < 0)
{
_malformedLine = true;
return;
}
}
// The length of the delimiter is the length of the closing quote (1) + any spaces + the length of the delimiter we matched if any
_delimiterLength = 1 + Limit - _index;
if (delimiterMatch.Success)
{
_delimiterLength += delimiterMatch.Length;
}
_fieldFinished = true;
return;
}
else
{
_field.Append(line[_index]);
_index += 1;
}
}
}
}
internal class TextFieldParser : IDisposable
{
private delegate int ChangeBufferFunction();
private bool _disposed;
private TextReader _reader;
private string[] _commentTokens = null;
private long _lineNumber = 1;
private bool _endOfData;
private string _errorLine = "";
private long _errorLineNumber = -1;
private FieldType _textFieldType = FieldType.Delimited;
private int[] _fieldWidths;
private int[] _fieldWidthsCopy;
private string[] _delimiters;
private string[] _delimitersCopy;
private Regex _delimiterRegex;
private Regex _delimiterWithEndCharsRegex;
private readonly int[] _whitespaceCodes = new int[] { '\u0009', '\u000B', '\u000C', '\u0020', '\u0085', '\u00A0', '\u1680', '\u2000', '\u2001', '\u2002', '\u2003', '\u2004', '\u2005', '\u2006', '\u2007', '\u2008', '\u2009', '\u200A', '\u200B', '\u2028', '\u2029', '\u3000', '\uFEFF' };
private Regex _beginQuotesRegex;
private bool _trimWhiteSpace = true;
private int _position;
private int _peekPosition;
private int _charsRead;
private bool _needPropertyCheck = true;
private const int DEFAULT_BUFFER_LENGTH = 4096;
private char[] _buffer = new char[DEFAULT_BUFFER_LENGTH];
private bool _hasFieldsEnclosedInQuotes = true;
private int _lineLength;
private string _spaceChars;
private readonly int _maxLineSize = 10000000;
private readonly int _maxBufferSize = 10000000;
private readonly bool _leaveOpen;
private readonly char[] _newLineChars = Environment.NewLine.ToCharArray();
public string[] CommentTokens
{
get => _commentTokens;
set
{
CheckCommentTokensForWhitespace(value);
_commentTokens = value;
_needPropertyCheck = true;
}
}
public bool EndOfData
{
get
{
if (_endOfData)
{
return _endOfData;
}
if ((_reader == null) || (_buffer == null))
{
_endOfData = true;
return true;
}
if (PeekNextDataLine() != null)
{
return false;
}
_endOfData = true;
return true;
}
}
public long LineNumber
{
get
{
if (_lineNumber != -1 && ((_reader.Peek() == -1) && (_position == _charsRead)))
{
// Side effect of a property. Not great. Just leaving it in for now.
CloseReader();
}
return _lineNumber;
}
}
public string ErrorLine => _errorLine;
public long ErrorLineNumber => _errorLineNumber;
public FieldType TextFieldType
{
get => _textFieldType;
set
{
ValidateFieldTypeEnumValue(value, "value");
_textFieldType = value;
_needPropertyCheck = true;
}
}
public int[] FieldWidths
{
get => _fieldWidths;
private set
{
if (value != null)
{
ValidateFieldWidthsOnInput(value);
_fieldWidthsCopy = (int[])value.Clone();
}
else
{
_fieldWidthsCopy = null;
}
_fieldWidths = value;
_needPropertyCheck = true;
}
}
public string[] Delimiters
{
get => _delimiters;
private set
{
if (value != null)
{
ValidateDelimiters(value);
_delimitersCopy = (string[])value.Clone();
}
else
{
_delimitersCopy = null;
}
_delimiters = value;
_needPropertyCheck = true;
_beginQuotesRegex = null;
}
}
public bool TrimWhiteSpace
{
get => _trimWhiteSpace;
set
{
_trimWhiteSpace = value;
}
}
public bool HasFieldsEnclosedInQuotes
{
get => _hasFieldsEnclosedInQuotes;
set
{
_hasFieldsEnclosedInQuotes = value;
}
}
private Regex BeginQuotesRegex
{
get
{
if (_beginQuotesRegex == null)
{
string pattern = string.Format(CultureInfo.InvariantCulture, "\\G[{0}]*\"", WhitespacePattern);
_beginQuotesRegex = new Regex(pattern, RegexOptions.CultureInvariant);
}
return _beginQuotesRegex;
}
}
private string EndQuotePattern => string.Format(CultureInfo.InvariantCulture, "\"[{0}]*", WhitespacePattern);
private string WhitespaceCharacters
{
get
{
StringBuilder builder = new StringBuilder();
int[] whitespaceCodes = _whitespaceCodes;
foreach (int code in whitespaceCodes)
{
char spaceChar = (char)code;
if (!CharacterIsInDelimiter(spaceChar))
{
builder.Append(spaceChar);
}
}
return builder.ToString();
}
}
private string WhitespacePattern
{
get
{
StringBuilder builder = new StringBuilder();
int[] whitespaceCodes = _whitespaceCodes;
for (int i = 0; i < whitespaceCodes.Length; i++)
{
int code = whitespaceCodes[i];
char spaceChar = (char)code;
if (!CharacterIsInDelimiter(spaceChar))
{
builder.Append("\\u" + code.ToString("X4", CultureInfo.InvariantCulture));
}
}
return builder.ToString();
}
}
public TextFieldParser(string path)
{
InitializeFromPath(path, Encoding.ASCII, detectEncoding: true);
}
public TextFieldParser(string path, Encoding defaultEncoding)
{
InitializeFromPath(path, defaultEncoding, detectEncoding: true);
}
public TextFieldParser(string path, Encoding defaultEncoding, bool detectEncoding)
{
InitializeFromPath(path, defaultEncoding, detectEncoding);
}
public TextFieldParser(Stream stream)
{
InitializeFromStream(stream, Encoding.ASCII, detectEncoding: true);
}
public TextFieldParser(Stream stream, Encoding defaultEncoding)
{
InitializeFromStream(stream, defaultEncoding, detectEncoding: true);
}
public TextFieldParser(Stream stream, Encoding defaultEncoding, bool detectEncoding)
{
InitializeFromStream(stream, defaultEncoding, detectEncoding);
}
public TextFieldParser(Stream stream, Encoding defaultEncoding, bool detectEncoding, bool leaveOpen)
{
_leaveOpen = leaveOpen;
InitializeFromStream(stream, defaultEncoding, detectEncoding);
}
public TextFieldParser(TextReader reader)
{
_reader = reader ?? throw new ArgumentNullException(nameof(reader));
ReadToBuffer();
}
public void SetDelimiters(params string[] delimiters)
{
Delimiters = delimiters;
}
public void SetFieldWidths(params int[] fieldWidths)
{
FieldWidths = fieldWidths;
}
public string ReadLine()
{
if ((_reader == null) || (_buffer == null))
{
return null;
}
ChangeBufferFunction BufferFunction = ReadToBuffer;
string line = ReadNextLine(ref _position, BufferFunction);
if (line == null)
{
FinishReading();
return null;
}
_lineNumber++;
return line.TrimEnd(_newLineChars);
}
public string[] ReadFields()
{
if ((_reader == null) || (_buffer == null))
{
return null;
}
ValidateReadyToRead();
switch (_textFieldType)
{
case FieldType.FixedWidth:
return ParseFixedWidthLine();
case FieldType.Delimited:
return ParseDelimitedLine();
default:
Debug.Fail("The TextFieldType is not supported");
return null;
}
}
///<summary>
/// Peek at <paramref name="numberOfChars"/> characters of the next data line without reading the line
///</summary>
///<param name="numberOfChars">The number of characters to look at in the next data line.</param>
///<returns>A string consisting of the first <paramref name="numberOfChars"/> characters of the next line. >If numberOfChars is greater than the next line, only the next line is returned</returns>
public string PeekChars(int numberOfChars)
{
if (numberOfChars <= 0)
{
throw new ArgumentException(string.Format(Strings.PositiveNumberOfCharacters, nameof(numberOfChars)));
}
if ((_reader == null) || (_buffer == null))
{
return null;
}
if (_endOfData)
{
return null;
}
string line = PeekNextDataLine();
if (line == null)
{
_endOfData = true;
return null;
}
line = line.TrimEnd(_newLineChars);
if (line.Length < numberOfChars)
{
return line;
}
return line.Substring(0, numberOfChars);
}
public string ReadToEnd()
{
if ((_reader == null) || (_buffer == null))
{
return null;
}
StringBuilder builder = new StringBuilder(_buffer.Length);
builder.Append(_buffer, _position, _charsRead - _position);
builder.Append(_reader.ReadToEnd());
FinishReading();
return builder.ToString();
}
public void Close()
{
CloseReader();
}
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (!_disposed)
{
Close();
}
_disposed = true;
}
}
private void ValidateFieldTypeEnumValue(FieldType value, string paramName)
{
if (value < FieldType.Delimited || value > FieldType.FixedWidth)
{
throw new InvalidEnumArgumentException(paramName, (int)value, typeof(FieldType));
}
}
private void CloseReader()
{
FinishReading();
if (_reader != null)
{
if (!_leaveOpen)
{
_reader.Close();
}
_reader = null;
}
}
private void FinishReading()
{
_lineNumber = -1L;
_endOfData = true;
_buffer = null;
_delimiterRegex = null;
_beginQuotesRegex = null;
}
private void InitializeFromPath(string path, Encoding defaultEncoding, bool detectEncoding)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
if (defaultEncoding == null)
{
throw new ArgumentNullException(nameof(defaultEncoding));
}
string fullPath = ValidatePath(path);
FileStream fileStreamTemp = new FileStream(fullPath, (FileMode.Open), (FileAccess.Read), (FileShare.ReadWrite));
_reader = new StreamReader(fileStreamTemp, defaultEncoding, detectEncoding);
ReadToBuffer();
}
private void InitializeFromStream(Stream stream, Encoding defaultEncoding, bool detectEncoding)
{
if (stream == null)
{
throw new ArgumentNullException(nameof(stream));
}
if (!stream.CanRead)
{
throw new ArgumentException(Strings.StreamDoesntSupportReading);
}
if (defaultEncoding == null)
{
throw new ArgumentNullException(nameof(defaultEncoding));
}
_reader = new StreamReader(stream, defaultEncoding, detectEncoding);
ReadToBuffer();
}
private string ValidatePath(string path)
{
if (!File.Exists(path))
{
throw new FileNotFoundException(Strings.FileNotFound);
}
return path;
}
private bool IgnoreLine(string line)
{
if (line == null)
{
return false;
}
string trimmedLine = line.Trim();
if (trimmedLine.Length == 0)
{
return true;
}
if (_commentTokens != null)
{
string[] commentTokens = _commentTokens;
foreach (string Token in commentTokens)
{
if (Token == string.Empty)
{
continue;
}
if (trimmedLine.StartsWith(Token, StringComparison.Ordinal))
{
return true;
}
if (line.StartsWith(Token, StringComparison.Ordinal))
{
return true;
}
}
}
return false;
}
private int ReadToBuffer()
{
Debug.Assert(_buffer != null, "There's no buffer");
Debug.Assert(_reader != null, "There's no StreamReader");
_position = 0;
int BufferLength = _buffer.Length;
Debug.Assert(BufferLength >= DEFAULT_BUFFER_LENGTH, "Buffer shrunk to below default");
if (BufferLength > DEFAULT_BUFFER_LENGTH)
{
BufferLength = DEFAULT_BUFFER_LENGTH;
_buffer = new char[BufferLength];
}
_charsRead = _reader.Read(_buffer, 0, BufferLength);
return _charsRead;
}
private int SlideCursorToStartOfBuffer()
{
Debug.Assert(_buffer != null, "There's no buffer");
Debug.Assert(_reader != null, "There's no StreamReader");
Debug.Assert((_position >= 0) && (_position <= _buffer.Length), "The cursor is out of range");
if (_position > 0)
{
int bufferLength = _buffer.Length;
char[] tempArray = new char[bufferLength];
Array.Copy(_buffer, _position, tempArray, 0, bufferLength - _position);
int charsRead = _reader.Read(tempArray, bufferLength - _position, _position);
_charsRead = _charsRead - _position + charsRead;
_position = 0;
_buffer = tempArray;
return charsRead;
}
return 0;
}
private int IncreaseBufferSize()
{
Debug.Assert(_buffer != null, "There's no buffer");
Debug.Assert(_reader != null, "There's no StreamReader");
_peekPosition = _charsRead;
int bufferSize = _buffer.Length + DEFAULT_BUFFER_LENGTH;
if (bufferSize > _maxBufferSize)
{
throw new Exception(Strings.ExceededMaxBufferSize);
}
char[] tempArray = new char[bufferSize];
Array.Copy(_buffer, tempArray, _buffer.Length);
int charsRead = _reader.Read(tempArray, _buffer.Length, DEFAULT_BUFFER_LENGTH);
_buffer = tempArray;
_charsRead += charsRead;
Debug.Assert(_charsRead <= bufferSize, "We've read more chars than we have space for");
return charsRead;
}
private string ReadNextDataLine()
{
ChangeBufferFunction BufferFunction = ReadToBuffer;
string line;
do
{
line = ReadNextLine(ref _position, BufferFunction);
_lineNumber++;
}
while (IgnoreLine(line));
if (line == null)
{
CloseReader();
}
return line;
}
private string PeekNextDataLine()
{
ChangeBufferFunction BufferFunction = IncreaseBufferSize;
SlideCursorToStartOfBuffer();
_peekPosition = 0;
string line;
do
{
line = ReadNextLine(ref _peekPosition, BufferFunction);
}
while (IgnoreLine(line));
return line;
}
private string ReadNextLine(ref int cursor, ChangeBufferFunction changeBuffer)
{
Debug.Assert(_buffer != null, "There's no buffer");
Debug.Assert((cursor >= 0) && (cursor <= _charsRead), "The cursor is out of range");
if (cursor == _charsRead && changeBuffer() == 0)
{
return null;
}
StringBuilder Builder = null;
// Consider replacing this do-while with a string search to take advantage of vectorization
do
{
for (int i = cursor; i <= _charsRead - 1; i++)
{
char Character = _buffer[i];
if (!(Character.Equals('\r') || Character.Equals('\n')))
{
continue;
}
if (Builder != null)
{
Builder.Append(_buffer, cursor, i - cursor + 1);
}
else
{
Builder = new StringBuilder(i + 1);
Builder.Append(_buffer, cursor, i - cursor + 1);
}
cursor = i + 1;
if (Character.Equals('\r'))
{
if (cursor < _charsRead)
{
if (_buffer[cursor].Equals('\n'))
{
cursor++;
Builder.Append("\n");
}
}
else if (changeBuffer() > 0 && _buffer[cursor].Equals('\n'))
{
cursor++;
Builder.Append("\n");
}
}
return Builder.ToString();
}
// Searched the whole buffer and haven't found an end of line. Save what we have and read more to the buffer
int Size = _charsRead - cursor;
if (Builder == null)
{
Builder = new StringBuilder(Size + 10);
}
Builder.Append(_buffer, cursor, Size);
}
while (changeBuffer() > 0);
return Builder.ToString();
}
private string[] ParseDelimitedLine()
{
string line = ReadNextDataLine();
if (line == null)
{
return null;
}
long currentLineNumber = _lineNumber - 1;
int index = 0;
List<string> Fields = new List<string>();
int lineEndIndex = GetEndOfLineIndex(line);
while (index <= lineEndIndex)
{
Match matchResult = null;
bool quoteDelimited = false;
if (HasFieldsEnclosedInQuotes)
{
matchResult = BeginQuotesRegex.Match(line, index);
quoteDelimited = matchResult.Success;
}
string field;
if (quoteDelimited)
{
// Move the Index beyond quote
index = matchResult.Index + matchResult.Length;
// Looking for the closing quote
QuoteDelimitedFieldBuilder endHelper = new QuoteDelimitedFieldBuilder(_delimiterWithEndCharsRegex, _spaceChars);
endHelper.BuildField(line, index);
if (endHelper.MalformedLine)
{
_errorLine = line.TrimEnd(_newLineChars);
_errorLineNumber = currentLineNumber;
throw new Exception(string.Format(Strings.CannotParseWithDelimiters, currentLineNumber));
}
if (endHelper.FieldFinished)
{
field = endHelper.Field;
index = endHelper.Index + endHelper.DelimiterLength;
}
else
{
// We may have an embedded line end character, so grab next line
do
{
int endOfLine = line.Length;
string newLine = ReadNextDataLine();
if (newLine == null)
{
_errorLine = line.TrimEnd(_newLineChars);
_errorLineNumber = currentLineNumber;
throw new Exception(string.Format(Strings.CannotParseWithDelimiters, currentLineNumber));
}
if (line.Length + newLine.Length > _maxLineSize)
{
_errorLine = line.TrimEnd(_newLineChars);
_errorLineNumber = currentLineNumber;
throw new Exception(string.Format(Strings.LineExceedsMaxLineSize, currentLineNumber));
}
line += newLine;
lineEndIndex = GetEndOfLineIndex(line);
endHelper.BuildField(line, endOfLine);
if (endHelper.MalformedLine)
{
_errorLine = line.TrimEnd(_newLineChars);
_errorLineNumber = currentLineNumber;
throw new Exception(string.Format(Strings.CannotParseWithDelimiters, currentLineNumber));
}
}
while (!endHelper.FieldFinished);
field = endHelper.Field;
index = endHelper.Index + endHelper.DelimiterLength;
}
if (_trimWhiteSpace)
{
field = field.Trim();
}
Fields.Add(field);
continue;
}
// Find the next delimiter
Match delimiterMatch = _delimiterRegex.Match(line, index);
if (delimiterMatch.Success)
{
field = line.Substring(index, delimiterMatch.Index - index);
if (_trimWhiteSpace)
{
field = field.Trim();
}
Fields.Add(field);
index = delimiterMatch.Index + delimiterMatch.Length;
continue;
}
field = line.Substring(index).TrimEnd(_newLineChars);
if (_trimWhiteSpace)
{
field = field.Trim();
}
Fields.Add(field);
break;
}
return Fields.ToArray();
}
private string[] ParseFixedWidthLine()
{
Debug.Assert(_fieldWidths != null, "No field widths");
string line = ReadNextDataLine();
if (line == null)
{
return null;
}
line = line.TrimEnd(_newLineChars);
StringInfo lineInfo = new StringInfo(line);
ValidateFixedWidthLine(lineInfo, _lineNumber - 1);
int index = 0;
int length = _fieldWidths.Length;
string[] Fields = new string[length];
for (int i = 0; i < length; i++)
{
Fields[i] = GetFixedWidthField(lineInfo, index, _fieldWidths[i]);
index += _fieldWidths[i];
}
return Fields;
}
private string GetFixedWidthField(StringInfo line, int index, int fieldLength)
{
string field = (fieldLength > 0) ? line.SubstringByTextElements(index, fieldLength) : ((index < line.LengthInTextElements) ? line.SubstringByTextElements(index).TrimEnd(_newLineChars) : string.Empty);
if (_trimWhiteSpace)
{
return field.Trim();
}
return field;
}
private int GetEndOfLineIndex(string line)
{
Debug.Assert(line != null, "We are parsing null");
int length = line.Length;
Debug.Assert(length > 0, "A blank line shouldn't be parsed");
if (length == 1)
{
Debug.Assert(!line[0].Equals('\r') && !line[0].Equals('\n'), "A blank line shouldn't be parsed");
return length;
}
checked
{
if (line[length - 2].Equals('\r') || line[length - 2].Equals('\n'))
{
return length - 2;
}
if (line[length - 1].Equals('\r') || line[length - 1].Equals('\n'))
{
return length - 1;
}
return length;
}
}
private void ValidateFixedWidthLine(StringInfo line, long lineNumber)
{
Debug.Assert(line != null, "No Line sent");
if (line.LengthInTextElements < _lineLength)
{
_errorLine = line.String;
_errorLineNumber = checked(_lineNumber - 1);
throw new Exception(string.Format(Strings.CannotParseWithFieldWidths, lineNumber));
}
}
private void ValidateFieldWidths()
{
if (_fieldWidths == null)
{
throw new InvalidOperationException(Strings.NullFieldWidths);
}
if (_fieldWidths.Length == 0)
{
throw new InvalidOperationException(Strings.EmptyFieldWidths);
}
checked
{
int widthBound = _fieldWidths.Length - 1;
_lineLength = 0;
int num = widthBound - 1;
for (int i = 0; i <= num; i++)
{
Debug.Assert(_fieldWidths[i] > 0, "Bad field width, this should have been caught on input");
_lineLength += _fieldWidths[i];
}
if (_fieldWidths[widthBound] > 0)
{
_lineLength += _fieldWidths[widthBound];
}
}
}
private void ValidateFieldWidthsOnInput(int[] widths)
{
Debug.Assert(widths != null, "There are no field widths");
int bound = widths.Length - 1;
for (int i = 0; i <= bound - 1; i++)
{
if (widths[i] < 1)
{
throw new ArgumentException(Strings.InvalidFieldWidths);
}
}
}
private void ValidateAndEscapeDelimiters()
{
if (_delimiters == null)
{
throw new Exception(Strings.NullDelimiters);
}
if (_delimiters.Length == 0)
{
throw new Exception(Strings.EmptyDelimiters);
}
int length = _delimiters.Length;
StringBuilder builder = new StringBuilder();
StringBuilder quoteBuilder = new StringBuilder();
quoteBuilder.Append(EndQuotePattern + "(");
for (int i = 0; i <= length - 1; i++)
{
if (_delimiters[i] != null)
{