简体   繁体   English

ReadStreamAsDT-Filehelpers和C#-如何使用FileHelpers动态读取CSV?

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

I am attempting to read in a CSV dynamically via FileHelpers and work with the CSV data as a datatable. 我正在尝试通过FileHelpers动态读取CSV并使用CSV数据作为数据表。 My CSV files will not be the same. 我的CSV文件将不同。 They will have different column headers and different amounts of columns. 它们将具有不同的列标题和不同数量的列。 I am using the ReadStreamAsDT method, but it seems to still want a structured class to initialize the FileHelperEngine. 我正在使用ReadStreamAsDT方法,但它似乎仍然想要结构化的类来初始化FileHelperEngine。 Any ideas? 有任何想法吗?

I had to use FileHelpers.RunTime and the DelimitedClassBuilder to create a DataTable from the file. 我必须使用FileHelpers.RunTimeDelimitedClassBuilder从文件创建一个DataTable 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 ? 您是否尝试过使用http://www.codeproject.com/KB/database/CsvReader.aspx You could leverage this library's parsing. 您可以利用该库的解析。 It's fast and reliable. 快速可靠。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM