private void ReadCVS(YaJiangBigDataContext _content,Type classType, string csvPath) {
//YaJiangBigDataContext 是EF的Contex,本例中可以替换为List<Object>
//csvPath 必须完整的物理路径 //classType 是用来存放csv数据的类的type int rowIndex = 0; using (var reader = new StreamReader(File.OpenRead(csvPath))) { string[] title = Array.Empty<string>();//保存标题 while (!reader.EndOfStream) { var line = reader.ReadLine(); if (!string.IsNullOrEmpty(line)) { string[] data= line.Split("\t"); //分隔符为\t if (rowIndex == 0) { //标题行 title = data; } else { //内容行,每行创建一个对象存储数据 object myObj = Activator.CreateInstance(classType); for (int i = 0; i < title.Length; i++) { PropertyInfo propertyInfo = classType.GetProperty(title[i]); Type pt = propertyInfo.PropertyType; propertyInfo.SetValue(myObj, propertyInfo.PropertyType.Name.Contains("Nullable") ? Convert.ChangeType(data[i], Nullable.GetUnderlyingType(pt)) : Convert.ChangeType(data[i], pt)); } _content.Add(myObj); //对象添加到EFContext中,也可以添加到List中 } } rowIndex++; } } }
标签:读取,title,c#,classType,propertyInfo,myObj,CSV,data,string From: https://www.cnblogs.com/fireicesion/p/18280579