我有这个简单的文件。
first name 1,last name 1
first name 2
first name 3,last name 3
first name 4,last name 4
案例1:我使用这个类从文件中读取数据:
[DelimitedRecord(",")] public partial class Person { private string firstName; [FieldNullValue("default last name")] private string lastName; public string FirstName { get { return firstName; } set { firstName = value; } } public string LastName { get { return lastName; } set { lastName = value; } } }
和这段代码
ExcelStorage provider = new ExcelStorage(typeof(Person)); provider.FileName = "data.csv"; Person[] res = provider.ExtractRecords() as Person[];
我正确获取数据,数组中的第二个元素具有姓氏 = 默认姓氏。
案例 2:我使用动态构建类型读取数据:
DelimitedClassBuilder cb = new DelimitedClassBuilder("Person2", ","); cb.AddField("firstName", typeof(string)); cb.AddField("lastName", typeof(string)); cb.LastField.FieldNullValue = "default last name"; DelimitedFileEngine engine = new DelimitedFileEngine(cb.CreateRecordClass()); DataTable dt = engine.ReadFileAsDT("data.csv");
我得到以下异常:Line: 2 Column: 0. Delimiter ',' not found after field 'firstName' (the record has less fields, the delimiter is wrong or the next field must be marked as optional).
让我们像这样更改文件,在第二行添加分隔符
first name 1,last name 1
first name 2,
first name 3,last name 3
first name 4,last name 4
- 案例 1:使用静态类型类读取:我得到相同的结果:有一个默认姓氏
- 案例2:使用动态创建的对象读取:不再刹车但没有默认值,只有“”