我需要在C#中读取CSV文件并将数据放入列表中,然后将数据转储到SQL数据库数据库。
我感兴趣的课程是使用CsvHelper。
这是CSV文件中的两个示例数据:
1,2013-05-14,NISSAN,059 7013,1995,VAN,Deisel,NISSAN,0000,NISSAN,Red,MARADANA,op1,description,p1.jpg+p2.jpg+p3.jpg,r1+r2+r3
2,2013-05-14,NISSAN2,059-7013,1995,VAN,Deisel,NISSAN,0000,NISSAN,Red,MARADANA,op1,description,p1.jpg+p2.jpg+p3.jpg,r1+r2+r3
这是CSV文件的类
class Vehicle
{
public int ID { get; set; }
public string ClosingDate { get; set; }
public string Model { get; set; }
public string Reg { get; set; }
public string YearOfManufacture { get; set; }
public string VehicleType { get; set; }
public string Fuel { get; set; }
public string Brand { get; set; }
public string Mileage { get; set; }
public string Make { get; set; }
public string Colour { get; set; }
public string VehicleYard { get; set; }
public string BasicOptions { get; set; }
public string Description { get; set; }
public List<string> Photos { get; set; }
public List<string> Regions { get; set; }
}
我尝试使用以下代码阅读CSV文件:
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
CsvHelperRead();
Console.Read();
}
private static void CsvHelperRead()
{
CsvConfiguration config = new CsvConfiguration();
config.HasHeaderRecord = false;
using (var reader = new CsvReader(new StreamReader(@"C:\Users\afshandc\Desktop\0729\vTest.csv"), config))
{
while (reader.Read())
{
Console.WriteLine(reader.GetField(1));
}
}
}
}
}
我需要阅读CSV文件并将其放到此列表中。
class CSV
{
public List<Vehicle> ReadVechileCSV()
{
}
}
答案 0 :(得分:1)
CsvHelperRead
中执行:
using (var reader = new CsvReader(new StreamReader(@"C:\Users\afshandc\Desktop\0729\vTest.csv"), config))
{
while (reader.Read())
{
string line = reader.GetField(1);
string[] classParams = line.Split(',');
Vehicle v = new Vehicle()
{
ID = int.Parse(classParams[0]),
ClosingDate = classParams[1],
Model = classParams[2],
Reg = classParams[3],
YearOfManufacture = classParams[4],
VehicleType = classParams[5],
Fuel = classParams[6],
Brand = classParams[7],
Mileage = classParams[8],
Make = classParams[9],
Colour = classParams[10],
VehicleYard = classParams[11],
BasicOptions = classParams[12],
Description = classParams[13],
Photos = GetJoinedByPlus(classParams[14]),
Regions = GetJoinedByPlus(classParams[15])
};
}
}
private List<string> GetJoinedByPlus(string p)
{
List<string> rtVal = new List<string>();
rtVal.AddRange(p.Split('+'));
return rtVal;
}
假设你有车辆的构造函数接收它的参数...