-
Notifications
You must be signed in to change notification settings - Fork 112
/
article.htm
1837 lines (1273 loc) · 69.4 KB
/
article.htm
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
<ul class="download">
<li><a href="https://github.com/mperdeck/LINQtoCSV">Source and sample code</a> </li>
<li><a href="http://nuget.org/List/Packages/LinqToCsv" target="_blank">NuGet package</a> </li>
</ul>
<h2>Contents</h2>
<ul>
<li><a href="#Introduction">Introduction</a> </li>
<li><a href="#Requirements">Requirements</a> </li>
<li><a href="#Installation">Installation</a> </li>
<li><a href="#How_to_use">Quick Start</a> </li>
<li><a href="#Write_Overloads">Write Overloads</a> </li>
<li><a href="#Read_Overloads">Read Overloads</a> </li>
<li><a href="#ReadingRawDataRows">Reading Raw Data Rows</a> </li>
<li><a href="#DeferredReading">Deferred Reading</a> </li>
<li><a href="#CsvFileDescription">CsvFileDescription</a> </li>
<li><a href="#CsvColumn_Attribute">CsvColumn Attribute</a> </li>
<li><a href="#Error_Handling">Error Handling</a> </li>
<li><a href="#History">History</a></li>
<li><a href="#Contribute">New Features and Bug Fixes</a></li>
</ul>
<h2><a id="Introduction"></a>Introduction</h2>
<p>This library makes it easy to use CSV files with LINQ queries. Its features include:</p>
<ul>
<li>Follows the <a target="_blank" href="http://www.creativyst.com/Doc/Articles/CSV/CSV01.htm">most common rules for CSV files</a>. Correctly handles data fields that contain commas and line breaks. </li>
<li>In addition to comma, most delimiting characters can be used, including tab for tab delimited fields. </li>
<li>Can be used with an <code>IEnumarable</code> of an anonymous class - which is often returned by a LINQ query. </li>
<li>Supports deferred reading. </li>
<li>Supports processing files with international date and number formats. </li>
<li>Supports different character encodings if you need them. </li>
<li>Recognizes a wide variety of date and number formats when reading files. </li>
<li>Provides fine control of date and number formats when writing files. </li>
<li>Robust error handling, allowing you to quickly find and fix problems in large input files. </li>
</ul>
<h2><a id="Requirements"></a>Requirements</h2>
<ul>
<li>To compile the library, you need a C# 2010 compiler or better, such as Visual Studio 2010 or Visual C# 2010 Express Edition. </li>
<li>To run the library code, you need to have the .NET 4.0 framework installed. </li>
</ul>
<h2><a id="Installation"></a>Installation</h2>
<p>
Simply install the <a href="http://nuget.org/List/Packages/LinqToCsv" target="_blank">NuGet package</a>.
</p>
<h2>Quick Start<a id="How_to_use"></a></h2>
<h3>Reading from a file</h3>
<ol>
<li>In your project, add a reference to the <em>LINQtoCSV.dll</em> you generated during <a href="#Installation">Installation</a>. </li>
<li>
The file will be read into an <code>IEnumerable<T></code>, where <code>T</code> is a data class that you define. The data records read from the file will be stored in objects of this data class. You could define a data class along these lines:
<pre lang="cs">using LINQtoCSV;
using System;
class Product
{
[CsvColumn(Name = "ProductName", FieldIndex = 1)]
public string Name { get; set; }
[CsvColumn(FieldIndex = 2, OutputFormat = "dd MMM HH:mm:ss")]
public DateTime LaunchDate { get; set; }
[CsvColumn(FieldIndex = 3, CanBeNull = false, OutputFormat = "C")]
public decimal Price { get; set; }
[CsvColumn(FieldIndex = 4)]
public string Country { get; set; }
[CsvColumn(FieldIndex = 5)]
public string Description { get; set; }
}</pre>
<p>With this definition, you could read into an <code>IEnumerable<Product></code>.</p>
<p>Although this example only uses properties, the library methods will recognize simple fields as well. Just make sure your fields/properties are public.</p>
<p>The optional <code>CsvColumn</code> attribute allows you to specify whether a field/property is required, how it should be written to an output file, etc. Full details are available <a href="#CsvColumn_Attribute">here</a>.</p>
</li>
<li>
Import the <code>LINQtoCSV</code> namespace at the top of the source file where you'll be reading the file:
<pre lang="cs">using LINQtoCSV;</pre>
</li>
<li>
Create a <code>CsvFileDescription</code> object, and initialize it with details about the file that you're going to read. It will look like this:
<pre lang="cs">CsvFileDescription inputFileDescription = new CsvFileDescription
{
SeparatorChar = ',',
FirstLineHasColumnNames = true
};</pre>
<p>This allows you to specify what character is used to separate data fields (comma, tab, etc.), whether the first record in the file holds column names, and a lot more (<a href="#CsvFileDescription">full details</a>).</p>
</li>
<li>
Create a <code>CsvContext</code> object:
<pre lang="cs">CsvContext cc = new CsvContext();</pre>
<p>It is this object that exposes the <code>Read</code> and <code>Write</code> methods you'll use to read and write files.</p>
</li>
<li>
Read the file into an <code>IEnumerable<T></code> using the <code>CsvContext</code> object's <code>Read</code> method, like this:
<pre lang="cs">IEnumerable<Product> products =
cc.Read<Product>("products.csv", inputFileDescription);</pre>
<p>This reads the file <em>products.csv</em> into the variable <code>products</code>, which is of type <code>IEnumerable<Product></code>.</p>
</li>
<li>
You can now access <code>products</code> via a LINQ query, a <code lang="cs">foreach</code> loop, etc.:
<pre lang="sql">var productsByName =
from p in products
orderby p.Name
select new { p.Name, p.LaunchDate, p.Price, p.Description };
// or ...
foreach (Product item in products) { .... }</pre>
</li>
</ol>
<p>To make it easier to get an overview, here is the code again that reads from a file, but now in one go:</p>
<pre lang="cs">CsvFileDescription inputFileDescription = new CsvFileDescription
{
SeparatorChar = ',',
FirstLineHasColumnNames = true
};
CsvContext cc = new CsvContext();
IEnumerable<Product> products =
cc.Read<Product>("products.csv", inputFileDescription);
// Data is now available via variable products.
var productsByName =
from p in products
orderby p.Name
select new { p.Name, p.LaunchDate, p.Price, p.Description };
// or ...
foreach (Product item in products) { .... }</pre>
<p>You'll find this same code in the SampleCode project in the <a href="https://github.com/mperdeck/LINQtoCSV">sources</a>. <a id="writing_to_a_file"></a></p>
<h3>Writing to a file</h3>
<p>This is very similar to <a href="#How_to_use">reading a file</a>.</p>
<ol>
<li>In your project, add a reference to <em>LINQtoCSV.dll</em>. </li>
<li>
The <code>Write</code> method takes a <code>IEnumerable<T></code> and writes each object of type <code>T</code> in the <code>IEnumerable<T></code> as a data record to the file. The definition of your data class could look like this:
<pre lang="cs">using LINQtoCSV;
using System;
class Product
{
[CsvColumn(Name = "ProductName", FieldIndex = 1)]
public string Name { get; set; }
[CsvColumn(FieldIndex = 2, OutputFormat = "dd MMM HH:mm:ss")]
public DateTime LaunchDate { get; set; }
[CsvColumn(FieldIndex = 3, CanBeNull = false, OutputFormat = "C")]
public decimal Price { get; set; }
[CsvColumn(FieldIndex = 4)]
public string Country { get; set; }
[CsvColumn(FieldIndex = 5)]
public string Description { get; set; }
}</pre>
<p>The optional <a href="#CsvColumn_Attribute"><code>CsvColumn</code></a> attribute allows you to specify such things as what date and number formats to use when writing each data field. Details for all CsvColumn properties (<code>CanBeNull</code>, <code>OutputFormat</code>, etc.) are available <a href="#CsvColumn_Attribute">here</a>.</p>
<p>Although this example only uses properties, you can also use simple fields.</p>
<p>The <code>Write</code> method will happily use an anonymous type for <code>T</code>, so you can write the output of a LINQ query right to a file. In that case, you obviously won't define <code>T</code> yourself. <a href="#WriteAnonymous">Later on</a>, you'll see an example of this.</p>
</li>
<li>
Import the <code>LINQtoCSV</code> namespace at the top of the source file where you'll be writing the file:
<pre lang="cs">using LINQtoCSV;</pre>
</li>
<li>
Make sure the data is stored in an object that implements <code>IEnumerable<T></code>, such as a <code>List<T></code>, or the <code>IEnumerable<T></code> returned by the <code>Read</code> method.
<pre lang="cs">List<Product> products2 = new List<Product>();
// Fill the list with products
// ...</pre>
</li>
<li>
Create a <a href="#CsvFileDescription"><code>CsvFileDescription</code></a> object, and initialize it with details about the file you will be writing, along these lines:
<pre lang="cs">CsvFileDescription outputFileDescription = new CsvFileDescription
{
SeparatorChar = '\t', // tab delimited
FirstLineHasColumnNames = false, // no column names in first record
FileCultureName = "nl-NL" // use formats used in The Netherlands
};</pre>
</li>
<li>
Create a <code>CsvContext</code> object:
<pre lang="cs">CsvContext cc = new CsvContext();</pre>
</li>
<li>
Invoke the <code>Write</code> method exposed by the <code>CsvContext</code> object to write the contents of your <code>IEnumerable<T></code> to a file:
<pre lang="cs">cc.Write(
products2,
"products2.csv",
outputFileDescription);</pre>
<p>This writes the <code>Product</code> objects in the variable <code>products2</code> to the file "<em>products2.csv</em>".</p>
</li>
</ol>
<p>Here is the code again that writes a file, but now in one go:</p>
<pre lang="cs">List<Product> products2 = new List<Product>();
// Fill the list with products
// ...
CsvFileDescription outputFileDescription = new CsvFileDescription
{
SeparatorChar = '\t', // tab delimited
FirstLineHasColumnNames = false, // no column names in first record
FileCultureName = "nl-NL" // use formats used in The Netherlands
};
CsvContext cc = new CsvContext();
cc.Write(
products2,
"products2.csv",
outputFileDescription);</pre>
<h3><a id="WriteAnonymous">Writing an IEnumerable of anonymous type</a></h3>
<p>If you have a LINQ query producing an <code>IEnumerable</code> of anonymous type, writing that <code>IEnumerable</code> to a file is no problem:</p>
<pre lang="cs">CsvFileDescription outputFileDescription = new CsvFileDescription
{
.....
};
CsvContext cc = new CsvContext();
// LINQ query returning IEnumerable of anonymous type
// into productsNetherlands
var productsNetherlands =
from p in products
where p.Country == "Netherlands"
select new { p.Name, p.LaunchDate, p.Price, p.Description };
// Write contents of productsNetherlands to file
cc.Write(
productsNetherlands,
"products-Netherlands.csv",
outputFileDescription);</pre>
<p>Here, a LINQ query selects all products for "Netherlands" from the variable <code>products</code>, and returns an <code>IEnumerable</code> holding objects of some anonymous type that has the fields <code>Name</code>, <code>LaunchDate</code>, <code>Price</code>, and <code>Description</code>. The <code>Write</code> method then writes those objects to the file <em>products-Netherlands.csv</em>.</p>
<h2><a id="Write_Overloads"></a>CsvContext.Write Overloads</h2>
<ul class="method">
<li><code lang="cs">Write<T>(IEnumerable<T> values, string fileName)</code> </li>
<li><code lang="cs">Write<T>(IEnumerable<T> values, string fileName, CsvFileDescription fileDescription)</code> </li>
<li><code>Write<T>(IEnumerable<T> values, TextWriter stream)</code> </li>
<li><code>Write<T>(IEnumerable<T> values, TextWriter stream, CsvFileDescription fileDescription)</code> </li>
</ul>
<p>Some interesting facts about these overloads:</p>
<ul>
<li>None of the overloads return a value. </li>
<li>Unlike the <code>Read</code> method, <code>Write</code> does not require that <code>T</code> has a parameterless constructor. </li>
<li>Overloads that take a stream write the data to the stream. Those that take a file name write the data to the file. </li>
<li>Overloads that do not take a <a href="#CsvFileDescription"><code>CsvFileDescription</code></a> object simply create one themselves, using the default values for the <code>CsvFileDescription</code> properties. </li>
</ul>
<h2><a id="Read_Overloads"></a>CsvContext.Read Overloads</h2>
<ul class="method">
<li><code lang="cs">Read<T>(string fileName)</code> </li>
<li><code lang="cs">Read<T>(string fileName, CsvFileDescription fileDescription)</code> </li>
<li><code>Read<T>(StreamReader stream)</code> </li>
<li><code>Read<T>(StreamReader stream, CsvFileDescription fileDescription)</code> </li>
</ul>
<p>Some interesting facts about these overloads:</p>
<ul>
<li>Each overload returns an <code>IEnumerable<T></code>. </li>
<li><code>T</code> must have a parameterless constructor. If you do not define a constructor for <code>T</code>, the compiler will generate a parameterless constructor for you. </li>
<li>Overloads that take a stream read the data from the stream. Those that take a file name read the data from the file. However, see the section on <a href="#DeferredReading">deferred reading</a>. </li>
<li>Overloads that do not take a <a href="#CsvFileDescription"><code>CsvFileDescription</code></a> object simply create one themselves, using the default values for the <code>CsvFileDescription</code> properties. </li>
</ul>
<h2><a id="ReadingRawDataRows"></a>Reading Raw Data Rows</h2>
<p>
Sometimes it's easier to read the raw data fields from the CSV file, instead of having them processed into objects by the library.
For example if different rows can have different formats, or if you don't know at compile time which field is going to hold what data.
</p>
<p>
You can make this happen by having your type T implement the interface <code>IDataRow</code>.
This interface is included in the library, so you don't have to write it yourself.
It essentially just describes a collection of <code>DataRowItem</code> objects:
</p>
<pre lang="cs">public interface IDataRow
{
// Number of data row items in the row.
int Count { get; }
// Clear the collection of data row items.
void Clear();
// Add a data row item to the collection.
void Add(DataRowItem item);
// Allows you to access each data row item with an array index, such as
// row[i]
DataRowItem this[int index] { get; set; }
}
</pre>
<p>
The <code>DataRowItem</code> class is also defined in the library. It describes each individual field within a data row:
</p>
<pre lang="cs">public class DataRowItem
{
...
// Line number of the field
public int LineNbr { get { ... } }
// Value of the field
public string Value { get { ... } }
}
</pre>
<p>
The line number is included in the <code>DataRowItem</code> class, because data rows can span multiple lines.
</p>
<p>
The easiest way to create a class that implements <code>IDataRow</code> is to derive it from <code>List<DataRowItem></code>:
</p>
<pre lang="cs">using LINQtoCSV;
internal class MyDataRow : List<DataRowItem>, IDataRow
{
}
</pre>
<p>
Now you can read the CSV file into a collection of <code>MyDataRow</code> objects:
</p>
<pre lang="cs">IEnumerable<MyDataRow> products =
cc.Read<MyDataRow>("products.csv", inputFileDescription);
</pre>
<p>
You can then access each individual field within each data row:
</p>
<pre lang="cs">foreach (MyDataRow dataRow in products)
{
string firstFieldValue = dataRow[0].Value;
int firstFieldLineNbr = dataRow[0].LineNbr;
string secondFieldValue = dataRow[1].Value;
int secondFieldLineNbr = dataRow[1].LineNbr;
...
}
</pre>
<h2><a id="DeferredReading"></a>Deferred Reading</h2>
<p>Here is how the <code>Read</code> overloads implement deferred reading:</p>
<ul>
<li>When you invoke the <code>Read</code> method (which returns an <code>IEnumerable<T></code>), no data is read yet. If using a file, the file is not yet opened. </li>
<li>When the Enumerator is retrieved from the <code>IEnumerable<T></code> (for example, when starting a <code lang="cs">foreach</code> loop), the file is opened for reading. If using a stream, the stream is rewound (seek to start of the stream). </li>
<li>Each time you retrieve a new object from the Enumerator (for example, while looping through a <code lang="cs">foreach</code>), a new record is read from the file or stream. </li>
<li>When you close the Enumerator (for example, when a <code lang="cs">foreach</code> ends or when you break out of it), the file is closed. If using a stream, the stream is left unchanged. </li>
</ul>
<p>This means that:</p>
<ul>
<li>If reading from a file, the file will be open for reading while you're accessing the <code>IEnumerable<T></code> in a <code lang="cs">foreach</code> loop. </li>
<li>The file can be updated in between accesses. You could access the <code>IEnumerable<T></code> in a <code lang="cs">foreach</code> loop, then update the file, then access the <code>IEnumerable<T></code> again in a <code lang="cs">foreach</code> loop to pick up the new data, etc. You only need to call <code>Read</code> once at the beginning, to get the <code>IEnumerable<T></code>. </li>
</ul>
<h2>CsvFileDescription<a id="CsvFileDescription"></a></h2>
<p>The <code>Read</code> and <code>Write</code> methods need some details about the file they are reading or writing, such as whether the first record contains column names.</p>
<p>As shown in the <a href="#How_to_use">Reading from a file</a> and <a href="#writing_to_a_file">Writing to a file</a> examples, you put those details in an object of type <code>CsvFileDescription</code>, which you then pass to the <code>Read</code> or <code>Write</code> method. This prevents lengthy parameter lists, and allows you to use the same details for multiple files.</p>
<p>A <code>CsvFileDescription</code> object has these properties:</p>
<ul class="property">
<li><a href="#SeparatorChar"><code>SeparatorChar</code></a> </li>
<li><a href="#QuoteAllFields"><code>QuoteAllFields</code></a> </li>
<li><a href="#FirstLineHasColumnNames"><code>FirstLineHasColumnNames</code></a> </li>
<li><a href="#EnforceCsvColumnAttribute"><code>EnforceCsvColumnAttribute</code></a> </li>
<li><a href="#FileCultureName"><code>FileCultureName</code></a> </li>
<li><a href="#TextEncoding"><code>TextEncoding</code></a> </li>
<li><a href="#DetectEncodingFromByteOrderMarks"><code>DetectEncodingFromByteOrderMarks</code></a> </li>
<li><a href="#MaximumNbrExceptions"><code>MaximumNbrExceptions</code></a> </li>
<li><a href="#NoSeparatorChar"><code>NoSeparatorChar</code></a> </li>
<li><a href="#UseFieldIndexForReadingData"><code>UseFieldIndexForReadingData</code></a> </li>
<li><a href="#IgnoreTrailingSeparatorChar"><code>IgnoreTrailingSeparatorChar</code></a> </li>
<li><a href="#IgnoreUnknownColumns"><code>IgnoreUnknownColumns</code></a> </li>
</ul>
<h3><a id="SeparatorChar">SeparatorChar</a></h3>
<table cellspacing="5" cellpadding="0" border="0">
<tbody>
<tr>
<td><strong>Type:</strong></td>
<td><code lang="cs">char</code></td>
</tr>
<tr>
<td><strong>Default: </strong></td>
<td>','</td>
</tr>
<tr>
<td><strong>Applies to: </strong></td>
<td>Reading and Writing</td>
</tr>
</tbody>
</table>
<h4>Example:</h4>
<pre lang="cs">CsvFileDescription fd = new CsvFileDescription();
fd.SeparatorChar = '\t'; // use tab delimited file
CsvContext cc = new CsvContext();
cc.Write(data, "file.csv", fd);</pre>
<p>The character used to separate fields in the file. This would be a comma for CSV files, or a '\t' for a tab delimited file.</p>
<p>You can use any character you like, except for white space characters or the double quote (").</p>
<h3><a id="QuoteAllFields">QuoteAllFields</a></h3>
<table cellspacing="5" cellpadding="0" border="0">
<tbody>
<tr>
<td><strong>Type:</strong></td>
<td><code lang="cs">bool</code></td>
</tr>
<tr>
<td><strong>Default: </strong></td>
<td><code lang="cs">false</code></td>
</tr>
<tr>
<td><strong>Applies to:</strong></td>
<td>Writing only</td>
</tr>
</tbody>
</table>
<h4>Example:</h4>
<pre lang="cs">fd.QuoteAllFields = true; // forces quotes around all fields</pre>
<p>When <code lang="cs">false</code>, <code>Write</code> only puts quotes around data fields when needed, to avoid confusion - for example, when the field contains the <code>SeparatorChar</code> or a line break.</p>
<p>When <code lang="cs">true</code>, <code>Write</code> surrounds all data fields with quotes.</p>
<h3><a name="FirstLineHasColumnNames">FirstLineHasColumnNames</a></h3>
<table cellspacing="5" cellpadding="0" border="0">
<tbody>
<tr>
<td><strong>Type:</strong></td>
<td><code lang="cs">bool</code></td>
</tr>
<tr>
<td><strong>Default:</strong></td>
<td><code lang="cs">true</code></td>
</tr>
<tr>
<td><strong>Applies to: </strong></td>
<td>Reading and Writing</td>
</tr>
</tbody>
</table>
<h4>Example:</h4>
<pre lang="cs">fd.FirstLineHasColumnNames = false; // first record does not have column headers</pre>
<p>When reading a file, tells <code>Read</code> whether to interpret the data fields in the first record in the file as column headers. </p>
<p>When writing a file, tells <code>Write</code> whether to write column headers as the first record of the file.</p>
<h3><a name="EnforceCsvColumnAttribute"></a>EnforceCsvColumnAttribute</h3>
<table cellpadding="3">
<tbody>
<tr>
<td><strong>Type:</strong></td>
<td><code lang="cs">bool</code></td>
</tr>
<tr>
<td><strong>Default: </strong></td>
<td><code lang="cs">false</code></td>
</tr>
<tr>
<td><strong>Applies to: </strong></td>
<td>Reading and Writing</td>
</tr>
</tbody>
</table>
<h4>Example:</h4>
<pre lang="cs">fd.EnforceCsvColumnAttribute = true; // only use fields with [CsvColumn] attribute</pre>
<p>When <code lang="cs">true</code>, <code>Read</code> only reads data fields into public fields and properties with the <code>[CsvColumn]</code> attribute, ignoring all other fields and properties. And, <code>Write</code> only writes the contents of public fields and properties with the <code>[CsvColumn]</code> attribute.</p>
<p>When <code lang="cs">false</code>, all public fields and properties are used.</p>
<h3><a name="FileCultureName"></a>FileCultureName</h3>
<table cellpadding="3">
<tbody>
<tr>
<td><strong>Type:</strong></td>
<td><code lang="cs">string</code></td>
</tr>
<tr>
<td><strong>Default: </strong></td>
<td>current system setting</td>
</tr>
<tr>
<td><strong>Applies to: </strong></td>
<td>Reading and Writing</td>
</tr>
</tbody>
</table>
<h4>Example:</h4>
<pre lang="cs">fd.FileCultureName = "en-US"; // use US style dates and numbers</pre>
<p>Different cultures use different ways to write dates and numbers. 23 May 2008 is 5/23/2008 in the United States (en-US) and 23/5/2008 in Germany (de-DE). Use the <code>FileCultureName</code> field to tell <code>Read</code> how to interpret the dates and numbers it reads from the file, and to tell <code>Write</code> how to write dates and numbers to the file.</p>
<p>By default, the library uses the current language/country setting on your system. So, if your system uses French-Canadian (fr-CA), the library uses that culture unless you override it with <code>FileCultureName</code>.</p>
<p>The library uses the same culture names as the .NET "<code>CultureInfo</code>" class (<a href="http://msdn2.microsoft.com/en-us/library/system.globalization.cultureinfo.aspx">full list of names</a>).</p>
<h3><a id="TextEncoding"></a>TextEncoding</h3>
<table cellpadding="3">
<tbody>
<tr>
<td><strong>Type:</strong></td>
<td><a target="_blank" href="http://msdn2.microsoft.com/en-us/library/system.text.encoding.aspx"><code>Encoding</code></a></td>
</tr>
<tr>
<td><strong>Default: </strong></td>
<td><code>Encoding.UTF8</code></td>
</tr>
<tr>
<td><strong>Applies to: </strong></td>
<td>Reading and Writing</td>
</tr>
</tbody>
</table>
<h4>Example:</h4>
<pre lang="cs">fd.TextEncoding = Encoding.Unicode; // use Unicode character encoding</pre>
<p>If the files that you read or write are in English, there is no need to set <code>TextEncoding</code>.</p>
<p>However, if you use languages other than English, the way the characters in your files are encoded may be an issue. You will want to make sure that the encoding used by the library matches the encoding used by any other programs (editors, spreadsheets) that access your files.</p>
<p>Specifically, if you write files with the Euro symbol, you may need to use Unicode encoding, as shown in the example.</p>
<h3>DetectEncodingFromByteOrderMarks<a id="DetectEncodingFromByteOrderMarks"></a></h3>
<table cellpadding="3">
<tbody>
<tr>
<td><strong>Type:</strong></td>
<td><code lang="cs">bool</code></td>
</tr>
<tr>
<td><strong>Default:</strong></td>
<td><code lang="cs">true</code></td>
</tr>
<tr>
<td><strong>Applies to: </strong></td>
<td>Reading only</td>
</tr>
</tbody>
</table>
<h4>Example:</h4>
<pre lang="cs">fd.DetectEncodingFromByteOrderMarks = false; // suppress encoding detection</pre>
<p>Related to <code>TextEncoding</code>. The default normally works fine.</p>
<p>Tells <code>Read</code> whether to detect the encoding of the input file by looking at the first three bytes of the file. Otherwise, it uses the encoding given in the <code>TextEncoding</code> property.</p>
<h3><a id="MaximumNbrExceptions"></a>MaximumNbrExceptions</h3>
<table cellpadding="3">
<tbody>
<tr>
<td><strong>Type:</strong></td>
<td><code lang="cs">int</code></td>
</tr>
<tr>
<td><strong>Default:</strong></td>
<td>100</td>
</tr>
<tr>
<td><strong>Applies to:</strong></td>
<td>Reading only</td>
</tr>
</tbody>
</table>
<h4>Example:</h4>
<pre lang="cs">fd.MaximumNbrExceptions = -1; // always read entire file before throwing AggregatedException</pre>
<p>Sets the maximum number of exceptions that will be aggregated into an <code>AggregatedException</code>.</p>
<p>To not have any limit and read the entire file no matter how many exceptions you get, set <code>AggregatedException</code> to -1.</p>
<p>For details about aggregated exceptions, see the <a href="#Error_Handling">error handling</a> section.</p>
<h3><a id="NoSeparatorChar">NoSeparatorChar</a></h3>
<table cellspacing="5" cellpadding="0" border="0">
<tbody>
<tr>
<td><strong>Type:</strong></td>
<td><code lang="cs">bool</code></td>
</tr>
<tr>
<td><strong>Default: </strong></td>
<td>false</td>
</tr>
<tr>
<td><strong>Applies to: </strong></td>
<td>Reading</td>
</tr>
</tbody>
</table>
<h4>Example:</h4>
<pre lang="cs">fd.NoSeparatorChar = true; // Fields are fixed width</pre>
<p>
Set this to true when the CSV file uses fixed width fields rather than separator characters.
</p>
<p>The number of characters is specified using the <a href="#CharLength">CharLength</a> property in the <a href="#CsvColumn_Attribute"><code>CsvColumnAttribute</code></a> class.</p>
<h3><a name="UseFieldIndexForReadingData"></a>UseFieldIndexForReadingData</h3>
<table cellpadding="3">
<tbody>
<tr>
<td><strong>Type:</strong></td>
<td><code>bool</code></a></td>
</tr>
<tr>
<td><strong>Default: </strong></td>
<td><code>false</code></td>
</tr>
<tr>
<td><strong>Applies to: </strong></td>
<td>Reading only</td>
</tr>
</tbody>
</table>
<h4>Example:</h4>
<pre lang="cs">fd.UseFieldIndexForReadingData = true;</pre>
<p>
Modifies the behaviour of the
<a href="#FieldIndex">FieldIndex</a> property of the
<a href="#CsvColumn_Attribute"><code>CsvColumnAttribute</code></a> class,
to make it suitable for fixed width fields.
See the description of the <a href="#FieldIndex">FieldIndex</a> property for details.
</p>
<h3><a id="IgnoreTrailingSeparatorChar"></a>IgnoreTrailingSeparatorChar</h3>
<table cellpadding="3">
<tbody>
<tr>
<td><strong>Type:</strong></td>
<td><code lang="cs">bool</code></td>
</tr>
<tr>
<td><strong>Default:</strong></td>
<td>false</td>
</tr>
<tr>
<td><strong>Applies to:</strong></td>
<td>Reading only</td>
</tr>
</tbody>
</table>
<h4>Example:</h4>
<pre lang="cs">fd.IgnoreTrailingSeparatorChar = true; // ignore separator character at the end of the line</pre>
<p>Consider following file: </p>
<p><code>column1;column2;column3;</code></p>
<p>Though it's not a canonical representation of CSV file, <code>IgnoreTrailingSeparatorChar</code> property tells <code>Read</code> to ignore separator character at the end of the line.</p>
<h3><a id="IgnoreUnknownColumns"></a>IgnoreUnknownColumns</h3>
<table cellpadding="3">
<tbody>
<tr>
<td><strong>Type:</strong></td>
<td><code lang="cs">bool</code></td>
</tr>
<tr>
<td><strong>Default:</strong></td>
<td>false</td>
</tr>
<tr>
<td><strong>Applies to:</strong></td>
<td>Reading only</td>
</tr>
</tbody>
</table>
<h4>Example:</h4>
<p>
There are cases where you don't need to read all the columns, but only a subset of them. Consider the following example of a CSV file containing a list of people:
</p>
<table cellspacing="5" cellpadding="0" border="0">
<tbody>
<tr>
<th>Id</th>
<th>Name</th>
<th>Last Name</th>
<th>Age</th>
<th>City</th>
</tr>
<tr>
<td>1</td>
<td>John</td>
<td>Doe</td>
<td>15</td>
<td>Washington</td>
</tr>
<tr>
<td>2</td>
<td>Jane</td>
<td>Doe</td>
<td>20</td>
<td>New York</td>
</tr>
</tbody>
</table>
<br>
Suppose you have the following class:
<pre lang="cs">
class Person
{
[CsvColumn(Name = "Name")]
public string Name { get ; set; }
[CsvColumn(Name = "Last Name")]
public string LastName { get; set; }
[CsvColumn(Name = "Age")]
public int Age { get; set; }
}
</pre>
<p>
Note that the input file has columns "Id" and "City" which are not listed in the class. This discrepancy would normally cause an exception.
</p>
<p>
However, if you set <pre lang="cs">fd.IgnoreUnknownColumns = true;</pre>
then the columns "Id" and "City" will be ignored without an exception.
</p>
<h2>CsvColumn Attribute<a id="CsvColumn_Attribute"></a></h2>
<p>As shown in the <a href="#How_to_use">Reading from a file</a> and <a href="#writing_to_a_file">Writing to a file</a> examples, you can decorate the public fields and properties of your data class with the <code>CsvColumn</code> attribute to specify such things as the output format for date and number fields.</p>
<p>Use of the <code>CsvColumn</code> attribute is optional. As long as the <a href="#EnforceCsvColumnAttribute"><code>EnforceCsvColumnAttribute</code></a> property of the <a href="#CsvFileDescription"><code>CsvFileDescription</code></a> object you pass into <code>Read</code> or <code>Write</code> is <code lang="cs">false</code>, those methods will look at all public fields and properties in the data class. They will then simply use the defaults shown with each <code>CsvColumn</code> property below.</p>
<p>The <code>CsvColumn</code> attribute has these properties:</p>
<ul class="property">
<li><a href="#Name"><code>Name</code></a> </li>
<li><a href="#CanBeNull"><code>CanBeNull</code></a> </li>
<li><a href="#NumberStyle"><code>NumberStyle</code></a> </li>
<li><a href="#OutputFormat"><code>OutputFormat</code></a> </li>
<li><a href="#FieldIndex"><code>FieldIndex</code></a> </li>
<li><a href="#CharLength"><code>CharLength</code></a> </li>
</ul>
<h3><a id="Name">Name</a></h3>
<table cellpadding="3">
<tbody>
<tr>
<td><strong>Type:</strong></td>
<td><code lang="cs">string</code></td>
</tr>
<tr>
<td><strong>Default:</strong></td>
<td>Name of the field or property</td>
</tr>
<tr>
<td><strong>Applies to:</strong></td>
<td>Reading and Writing</td>
</tr>
</tbody>
</table>
<h4>Example:</h4>
<pre lang="cs">[CsvColumn(Name = "StartDate")]
public DateTime LaunchDate { get; set; }</pre>
<p>The <code>Read</code> and <code>Write</code> methods normally assume that the data fields in the file have the same names as the corresponding fields or properties in the class. Use the <code>Name</code> property to specify another name for the data field.</p>
<h3><a id="CanBeNull">CanBeNull</a></h3>
<table cellpadding="3">
<tbody>
<tr>
<td><strong>Type:</strong></td>
<td><code lang="cs">bool</code></td>
</tr>
<tr>
<td><strong>Default: </strong></td>
<td><code lang="cs">true</code></td>
</tr>
<tr>
<td><strong>Applies to: </strong></td>
<td>Reading only</td>
</tr>
</tbody>
</table>
<pre lang="cs">[CsvColumn(CanBeNull = false)]
public DateTime LaunchDate { get; set; }</pre>
<p>If <code lang="cs">false</code>, and a record in the input file does not have a value for this field or property, then the <code>Read</code> method generates a <a href="#MissingRequiredFieldException"><code>MissingRequiredFieldException</code></a> exception.</p>
<h3><a id="FieldIndex">FieldIndex</a></h3>
<table cellpadding="3">
<tbody>
<tr>
<td><strong>Type:</strong></td>
<td><code lang="cs">bool</code></td>
</tr>
<tr>
<td><strong>Default:</strong></td>
<td><code>Int32.MaxValue</code></td>
</tr>