CsvHelper กับ .NET 6 Console

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

CsvHelper เวอร์ชัน Version 19.0.0 ดู Console ใช้ CsvHelper

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

PM> Install-Package CsvHelper -Version 27.2.1

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

using CsvHelper;
using CsvHelper.Configuration;
using System.Globalization;
using System.Reflection;
using System.Xml;

namespace ConsoleApp1;
class Program
{
    public static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(Program));

    static void Main()
    {
        XmlDocument log4netConfig = new XmlDocument();
        log4netConfig.Load(File.OpenRead("log4net.config"));
        var repo = log4net.LogManager.CreateRepository(Assembly.GetEntryAssembly(),
                   typeof(log4net.Repository.Hierarchy.Hierarchy));
        log4net.Config.XmlConfigurator.Configure(repo, log4netConfig["log4net"]);

        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);
            var config = new CsvConfiguration(CultureInfo.CurrentCulture) { Delimiter = "|" };
            using (var writer = new StreamWriter(string.Format("{0}/file.csv", AppDomain.CurrentDomain.BaseDirectory)))
            using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
            {
                csv.WriteRecords(records);
            }
            log.Info("************** END **************");
            log.Info("");
        }
        catch (Exception ex)
        {
            log.Error(ex.Message);
            log.Error(ex.ToString());
        }
    }
}

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

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

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

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

3.อ่านไฟล์ CSV

using CsvHelper;
using CsvHelper.Configuration;
using System.Globalization;
using System.Reflection;
using System.Xml;

namespace ConsoleApp1;
class Program
{
    public static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(Program));

    static void Main()
    {
        XmlDocument log4netConfig = new XmlDocument();
        log4netConfig.Load(File.OpenRead("log4net.config"));
        var repo = log4net.LogManager.CreateRepository(Assembly.GetEntryAssembly(),
                   typeof(log4net.Repository.Hierarchy.Hierarchy));
        log4net.Config.XmlConfigurator.Configure(repo, log4netConfig["log4net"]);

        try
        {
            string filename = string.Format("{0}file.csv", AppDomain.CurrentDomain.BaseDirectory);
            log.Info(string.Format("filename  = '{0}'", filename));
            var config = new CsvConfiguration(CultureInfo.CurrentCulture) { Delimiter = "|" };
            using (var reader = new StreamReader(filename))
            using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
            {
                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));
                }
            }
        }
        catch (Exception ex)
        {
            log.Error(ex.Message);
            log.Error(ex.ToString());
        }
    }
}

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'