Home > Back-end >  How to insert a list into a CSV file and then read it back into the list?
How to insert a list into a CSV file and then read it back into the list?

Time:11-24

How can I put my list into a csv file and then read data back into that list from the file?

Here is my list:

List<Student> students = new List<Student>();
Student newstudent = new Student();
newstudent.studentID = txt_sID.Text;
newstudent.studentName = txt_sName.Text;
newstudent.studentAge = txt_sAge.Text;
students.Add(newstudent);

Many thanks for your time.

CodePudding user response:

Well , you need reader and writer :

using System;
using System.Globalization;
using System.IO;
using CsvHelper;
using CsvHelper.Configuration;

var csvConfig = new CsvConfiguration(CultureInfo.CurrentCulture)
{
    HasHeaderRecord = false,
    Comment = '#',
    AllowComments = true,
    Delimiter = ";",
};


public void Reader()
{
    using var streamReader = File.OpenText("students.csv");
    using var csvReader = new CsvReader(streamReader, csvConfig);
    List<Student> students = new List<Student>();
    while (csvReader.Read())
    {
        var studentID = csvReader.GetField(0);
        var studentName = csvReader.GetField(1);
        var studentAge = csvReader.GetField(2);

        Student newstudent = new();
        newstudent.studentID = studentID ;
        newstudent.studentName = studentName;
        newstudent.studentAge = studentAge;
        students.Add(newstudent);
    }
}

pubnlic void Writer()
{
    List<Student> students = new List<Student>();
    Student newstudent = new();
    newstudent.studentID = txt_sID.Text;
    newstudent.studentName = txt_sName.Text;
    newstudent.studentAge = txt_sAge.Text;
    students.Add(newstudent);
    using var streamWrit = new StreamWriter("students.csv");
    using var csvWriter = new CsvWriter(streamWrit, csvConfig);

// if you want header
    csvWriter.WriteHeader<Student>();

    csvWriter.NextRecord();
    csvWriter.WriteRecords(students);
}
  • Related