关于filehelper库的快速问题:
我已经使用文件助手引擎来读取流,做我的验证,如果CSV文件没有得到头,我们需要匹配/映射到我的模型:即
id,姓名,年龄,电话,性别,但CSV可能并不总是以这种格式/顺序出现,我们需要使用每个列的下拉列表来匹配它们。
我有没有办法做到这一点?
谢谢,
发布于 2014-08-22 22:06:19
简而言之,不是。但您可以动态创建依赖类:
因为在JSON文件中有可能的字段列表,所以我建议对第一个数据行执行一个基本的System.IO ReadLine,然后根据分隔符解析各个头文件。即:
string headerString;
var headers = new List<String>();
var file = new System.IO.StreamReader("C:\\myFile.txt");
headerString = file.ReadLine();
file.Close();
headers = headerString.Split(',').ToList();现在您有了第一行的字符串列表,可以与您的JSON文件进行匹配。然后,您可以使用System.Reflection.Emit (下面引用的链接)创建依赖类
typeBuilder.SetParent(typeof(MyFileHelperBaseClass));
// can place the property definitions in a for loop against your headers
foreach(string h in headers){
typeBuilder.DefineProperty("<header/col#>", ..., typeof(System.Int32), null);
}stackoverflow article 14724822: How Can I add properties to a class on runtime in C#?
文件帮助器有时会变得有点挑剔,所以需要一些调整。
希望这能有所帮助
发布于 2014-08-26 20:18:11
您可以使用File.ReadLines(@"C:\myfile.txt").First()读取第一行并获取标题。
然后,您可以只使用FileHelpers CodeBuilder来构建运行时类。从带分隔符的csv文件示例:
DelimitedClassBuilder cb = new DelimitedClassBuilder("Customers", ",");
cb.IgnoreFirstLines = 1;
cb.IgnoreEmptyLines = true;
cb.AddField("BirthDate", typeof(DateTime));
cb.LastField.TrimMode = TrimMode.Both;
cb.LastField.FieldNullValue = DateTime.Today;
cb.AddField("Name", typeof(string));
cb.LastField.FieldQuoted = true;
cb.LastField.QuoteChar = '"';
cb.AddField("Age", typeof(int));
engine = new FileHelperEngine(cb.CreateRecordClass());
DataTable dt = engine.ReadFileAsDT("testCustomers.txt");然后,您可以遍历生成的数据表。
https://stackoverflow.com/questions/25447954
复制相似问题