[.Net Tools][C#.NET] 使用 CsvHelper 處理 CSV 檔案格式

[.Net Tools][C#.NET] 使用 CsvHelper 處理 CSV 檔案格式

除了上篇介紹的 [.Net Tools][C#.NET] 使用 LinqToCSV 處理 CSV 檔案格式,在NuGet上還有一個叫CsvHelper,不過在NuGet上只會幫我安裝 .NET4.0 的版本

image

若你的專案不是.Net4.0,作者的github上寫著 .NET3.5是 1.2.0 版,這必須自己手動鍵入版本

https://github.com/JoshClose/CsvHelper/wiki

image

http://docs.nuget.org/docs/start-here/using-the-package-manager-console 安裝方式參考。

https://github.com/JoshClose/CsvHelper/wiki CsvHelper用法參考。

加入CsvHelper.dll參考後,會用到以下兩個命名空間


using CsvHelper.Configuration;
定義類別

{
    [CsvField(Name = "批號", Index = 0)]
    public string BatchID { get; set; }

    [CsvField(Name = "發送時間", Index = 1)]
    public string SentTime { get; set; }

    [CsvField(Name = "訊息主旨", Index = 2)]
    public string SentSubject { get; set; }

    [CsvField(Name = "發送內容", Index = 3)]
    public string SentContent { get; set; }

    [CsvField(Name = "發送通數", Index = 4)]
    public string SentCount { get; set; }

    [CsvField(Name = "成功收訊", Index = 5)]
    public string Successed { get; set; }

    [CsvField(Name = "傳送中通數", Index = 6)]
    public string SendingCount { get; set; }

    [CsvField(Name = "預約傳送通數", Index = 7)]
    public string PreSendCount { get; set; }

    [CsvField(Name = "逾期收訊", Index = 8)]
    public string Timeout { get; set; }

    [CsvField(Name = "回覆通數", Index = 9)]
    public string ReplyCount { get; set; }

    public override string ToString()
    {
        return this.BatchID;
    }
}
準備好檔案,跟上一篇一樣
image
CsvReader / CsvWriter 是用來讀寫csv檔案用的

///A test for ReadCsvFile
///</summary>
[TestMethod(), DeploymentItem("readFile.txt")]
public void CsvHelpCsvTest()
{
    using (FileStream fileStream = new FileStream("readFile.txt", FileMode.Open, FileAccess.Read))
    using (StreamReader reader = new StreamReader(fileStream, Encoding.UTF8))
    using (CsvReader csv = new CsvReader(reader))
    {
        csv.Read();
        var content = csv.GetRecords<BatchIdResponse>();
    }
}
設定中斷所觀察的結果,輕而易舉就將資料倒回 BatchIdResponse 集合裡面了
image

若有謬誤,煩請告知,新手發帖請多包涵


Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET

Image result for microsoft+mvp+logo