static void Main(string[] args) { var students = new List<StudentInfo> { new StudentInfo { ID = 1, Name = "張三", Age = 20, Class = "終極一班", Gender = "男", Address = "北京市東城區(qū)" }, new StudentInfo { ID = 2, Name = "李四", Age = 21, Class = "終極一班", Gender = "女", Address = "上海市黃浦區(qū)" }, new StudentInfo { ID = 3, Name = "王五", Age = 22, Class = "終極一班", Gender = "男", Address = "廣州市越秀區(qū)" }, new StudentInfo { ID = 4, Name = "趙六", Age = 20, Class = "終極二班", Gender = "女", Address = "深圳市福田區(qū)" }, new StudentInfo { ID = 5, Name = "孫七", Age = 23, Class = "終極二班", Gender = "男", Address = "杭州市西湖區(qū)" }, new StudentInfo { ID = 6, Name = "周八", Age = 24, Class = "終極二班", Gender = "女", Address = "南京市玄武區(qū)" }, new StudentInfo { ID = 7, Name = "吳九", Age = 22, Class = "終極二班", Gender = "男", Address = "成都市錦江區(qū)" }, new StudentInfo { ID = 8, Name = "小袁", Age = 21, Class = "終極三班", Gender = "女", Address = "重慶市渝中區(qū)" }, new StudentInfo { ID = 9, Name = "大姚", Age = 20, Class = "終極三班", Gender = "男", Address = "武漢市武昌區(qū)" }, new StudentInfo { ID = 10, Name = "追逐時光者", Age = 23, Class = "終極三班", Gender = "女", Address = "長沙市天心區(qū)" } };
//寫入CSV文件數(shù)據(jù) using var writer = new StreamWriter(@".\StudentInfoFile.csv"); using var csvWriter = new CsvWriter(writer, CultureInfo.InvariantCulture); csvWriter.WriteRecords(students); }
讀取CSV文件數(shù)據(jù)
快速讀取上面寫入到StudentInfoFile.csv中的數(shù)據(jù)。
static void Main(string[] args) { //讀取CSV文件數(shù)據(jù) using var reader = new StreamReader(@".\StudentInfoFile.csv"); using var csvReader = new CsvReader(reader, CultureInfo.InvariantCulture); var getStudentInfos = csvReader.GetRecords<StudentInfo>().ToList(); }