FileHelper ReadFile()返回null

时间:2014-06-18 14:23:08

标签: c# filehelpers

我正在使用优秀的FileHelpers库(版本2.9.9)。但是我现在已经被困了几个小时而且我无法解决这个问题。我想将我的文件加载到CustomerClass对象的数组中。我想使用DelimitedClassBuilder动态更改字段的顺序。我在Stackoverflow上找到了一个答案,它显示了如何做到https://stackoverflow.com/a/8833322/767926。即使按照这个答案,我也无法做到。但是,如果我直接使用FileHelperEngine而不是DelimitedClassBuilder,它可以正常工作。有人可以帮帮我吗?

这是我想要从csv文件创建数组的对象:

[DelimitedRecord(";")]
public class CustomerClass
{
    public string CustomerId;

    public string FirstName;

    public string LastName;
}

这是我用来创建数组的代码:

public void ReadFile()
{
    DelimitedClassBuilder cb = new DelimitedClassBuilder("CustomerClass", ";");
    cb.AddField("CustomerId", typeof(string));
    cb.AddField("FirstName", typeof(string));
    cb.AddField("LastName", typeof(string));

    FileHelperEngine engine = new FileHelperEngine(cb.CreateRecordClass());
    engine.ErrorMode = ErrorMode.IgnoreAndContinue;

    string filename = @"C:\temp\customerfile.csv";

    DataTable dt = engine.ReadFileAsDT(filename); // Works fine
    object[] test = engine.ReadFile(filename) as object[]; // Works fine

    CustomerClass[] customers = engine.ReadFile(filename) as CustomerClass[]; // Returns null (probably because the 'cast' is invalid, see line below)
    customers = (CustomerClass[])engine.ReadFile(filename); // Throws InvalidCastException (Unable to cast object of type 'CustomerClass[]' to type 'MyNamespace.CustomerClass[]'.)
}

这是文件内容:

  

客户ID;姓;名字

     

1;詹姆斯;布朗

     

2;罗伯特;米勒

     

3;大卫;绿色

2 个答案:

答案 0 :(得分:0)

尝试完全限定的班级名称:

DelimitedClassBuilder cb = new DelimitedClassBuilder("MyNamespace.CustomerClass", ";");

答案 1 :(得分:0)

根据您提供的评论,我建议使用以下内容:

var customers = engine.ReadFile(filename)
                      .Cast<*type of the class coming back from ReadFile*>()
                      .Select(c => new MyNamespace.CustomerClass()
                                       {
                                            CustomerId = c.CustomerId,
                                            FirstName = c.FirstName,
                                            LastName = c.LastName
                                       })
                      .ToArray();

您需要提供从engine.ReadFile返回到Cast的号码的类的类型。然后,对Select的调用将为每个返回的客户创建CustomerClass的实例。