[.Net Tool][C#.NET] 使用 LinqToCSV 處理 CSV 檔案格式
好用的NuGet裡有蠻多處理CSV的library,這次要介紹的是 LinqToCSV
官網參考
http://www.aspnetperformance.com/post/LINQ-to-CSV-library.aspx
http://www.codeproject.com/Articles/25133/LINQ-to-CSV-library
加入LinqToCSV參考後,匯入命名空間
定義類別
{
[CsvColumn(Name = "批號", FieldIndex = 0)]
public string BatchID { get; set; }
[CsvColumn(Name = "發送時間", FieldIndex = 1)]
public string SentTime { get; set; }
[CsvColumn(Name = "訊息主旨", FieldIndex = 2)]
public string SentSubject { get; set; }
[CsvColumn(Name = "發送內容", FieldIndex = 3)]
public string SentContent { get; set; }
[CsvColumn(Name = "發送通數", FieldIndex = 4)]
public string SentCount { get; set; }
[CsvColumn(Name = "成功收訊", FieldIndex = 5)]
public string Successed { get; set; }
[CsvColumn(Name = "傳送中通數", FieldIndex = 6)]
public string SendingCount { get; set; }
[CsvColumn(Name = "預約傳送通數", FieldIndex = 7)]
public string PreSendCount { get; set; }
[CsvColumn(Name = "逾期收訊", FieldIndex = 8)]
public string Timeout { get; set; }
[CsvColumn(Name = "回覆通數", FieldIndex = 9)]
public string ReplyCount { get; set; }
public override string ToString()
{
return this.BatchID;
}
}
準備文檔
撰寫程式碼,使用 CsvContext.Read 方法讀取File
///A test for ReadCsvFile
///</summary>
[TestMethod(), DeploymentItem("readFile.txt")]
public void LinqToCsvTest()
{
CsvContext csv = new CsvContext();
var content = csv.Read<BatchIdResponse>("readFile.txt");
Assert.AreNotEqual(null, content);
}
設定中斷觀察變數是否真的將csv資料轉換成BatchIdResponse Class
若有謬誤,煩請告知,新手發帖請多包涵
Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET