ReadStreamAsDT - Filehelpers and C# - How do I dynamically read in a CSV using filehelpers?

随声附和 提交于 2019-12-01 10:11:21

I had to use FileHelpers.RunTime and the DelimitedClassBuilder to create a DataTable from the file. Here is my method. If I get more time, I will explain this better.

private static DataTable CreateDataTableFromFile(byte[] importFile) {
    var cb = new DelimitedClassBuilder("temp", ",") { IgnoreFirstLines = 0, IgnoreEmptyLines = true, Delimiter = "," };
    var ms = new MemoryStream(importFile); 
    var sr = new StreamReader(ms); 
    var headerArray = sr.ReadLine().Split(',');
    foreach (var header in headerArray) { 
        cb.AddField(header, typeof(string)); 
        cb.LastField.FieldQuoted = true; 
        cb.LastField.QuoteChar = '"'; 
    }
    var engine = new FileHelperEngine(cb.CreateRecordClass());
    return engine.ReadStreamAsDT(sr);
}

Obviously, there is a lot of validation along with other logic taking place around this method, but I do not have much time right now to dive into it. Hope this helps!

Have you tried using http://www.codeproject.com/KB/database/CsvReader.aspx ? You could leverage this library's parsing. It's fast and reliable.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!