Console ใช้ CsvHelper

  1. ติดตั้ง CsvHelper ผ่าน NuGet
  2. เขียนไฟล์ CSV
  3. อ่านไฟล์ CSV

1.ติดตั้ง CsvHelper ผ่าน NuGet

PM> Install-Package CsvHelper -Version 19.0.0

2.เขียนไฟล์ CSV

static void Main(string[] args)
{
    try
    {
        log.Info("*********************************");
        log.Info("************* BEGIN *************");
        log.Info(AppDomain.CurrentDomain.FriendlyName);

        var records = new List<Foo>
        {
            new Foo { Id = 1, Name = "one" },
            new Foo { Id = 2, Name = "two" },
        };

        records.Add(new Foo { Id = 3, Name = "three" });

        Foo foo = new Foo();
        foo.Id = 4;
        foo.Name = "four";
        records.Add(foo);

        using (var writer = new StreamWriter(string.Format("{0}/file.csv", AppDomain.CurrentDomain.BaseDirectory)))
        using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
        {
            csv.Configuration.Delimiter = "|";
            csv.WriteRecords(records);
        }

        log.Info("************** END **************");
        log.Info("");
    }
    catch (Exception ex)
    {
        log.Error(ex.Message);
        log.Error(ex.ToString());
    }
} // end main

public class Foo
{
    public int Id { get; set; }
    public string Name { get; set; }
}

บรรทัดที่ 25 กำหนด delimiter เป็น Pipe (ค่า default จะเป็น comma)

ตัวอย่างไฟล์ที่ได้

Id|Name
1|one
2|two
3|three
4|four

3.อ่านไฟล์ CSV

static void Main(string[] args)
{
    try
    {
        log.Info("*********************************");
        log.Info("************* BEGIN *************");
        log.Info(AppDomain.CurrentDomain.FriendlyName);

        string filename = string.Format("{0}file.csv", AppDomain.CurrentDomain.BaseDirectory);
        log.Info(string.Format("filename  = '{0}'", filename));

        using (var reader = new StreamReader(filename))
        using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
        {
            csv.Configuration.Delimiter = "|";
            var records = csv.GetRecords<Foo>();

            var foo = records.ToList();
            int count = foo.Count();
            log.Info(string.Format("count = '{0}' ", count));

            for (int r = 0; r < count; r++)
            {
                log.Info(string.Format("Id = '{0}', Name = '{1}'", foo[r].Id, foo[r].Name));
            }
        }

        log.Info("************** END **************");
        log.Info("");
    }
    catch (Exception ex)
    {
        log.Error(ex.Message);
        log.Error(ex.ToString());
    }
} // end main

public class Foo
{
    public int Id { get; set; }
    public string Name { get; set; }
}

ตัวอย่าง output

count = '4'
Id = '1', Name = 'one'
Id = '2', Name = 'two'
Id = '3', Name = 'three'
Id = '4', Name = 'four'