การอ่านไฟล์ CSV ด้วย StreamReader
CSV (Comma-Separated Values) เป็นรูปแบบไฟล์ข้อมูลแบบทابلาร์ที่แยกคอลัมน์ด้วยคอมมา ใช้กันอย่างแพร่หลายในองค์กร ใน C# ใช้ StreamReader (อยู่ใน System.IO) อ่านไฟล์ได้อย่างมีประสิทธิภาพ
เมธอดสำคัญ
File.OpenRead(path)- เปิดไฟล์เพื่ออ่าน (คืน FileStream)StreamReader.ReadLine()- อ่านบรรทัดต่อบรรทัด คืน null เมื่อจบไฟล์string.Split(',')- แยกค่าด้วยคอมมา
ตัวอย่างพื้นฐาน: อ่าน CSV ทั้งไฟล์เก็บใน List
using System;
using System.Collections.Generic;
using System.IO;
class Program
{
public static void Main()
{
string filePath = @"C:\Users\Koushik\Desktop\Questions\ConsoleApp\Data.csv";
if (!File.Exists(filePath))
{
Console.WriteLine("ไฟล์ไม่มีอยู่");
return;
}
List<string> allValues = new List<string>();
using (StreamReader reader = new StreamReader(File.OpenRead(filePath)))
{
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
if (string.IsNullOrWhiteSpace(line)) continue;
string[] values = line.Split(',');
allValues.AddRange(values);
}
}
// แสดงผล
foreach (var value in allValues)
{
Console.WriteLine(value);
}
}
}
ไฟล์ Data.csv ตัวอย่าง:
A,B,C
ผลลัพธ์:
A B C
ตัวอย่างขั้นสูง: อ่าน CSV เป็น Object (ใช้ CsvHelper แนะนำ)
สำหรับ CSV จริงที่มี quote, escape character, header แนะนำใช้ไลบรารี CsvHelper (NuGet: CsvHelper)
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using CsvHelper;
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public string City { get; set; }
}
class Program
{
public static void Main()
{
using (var reader = new StreamReader("people.csv"))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
var records = csv.GetRecords<Person>().ToList();
foreach (var person in records)
{
Console.WriteLine($"{person.Name}, {person.Age}, {person.City}");
}
}
}
}
ข้อควรระวังในการ Split(',') แบบง่าย
| ปัญหา | ตัวอย่าง | ผลลัพธ์ผิด |
|---|---|---|
| ค่าที่มีคอมมาภายใน | "Smith, John",25 | แยกเป็น 3 ส่วน |
| ค่าที่มี newline | "Line1\nLine2",30 | อ่านบรรทัดไม่ครบ |
| Quote character | "He said ""Hi""",40 | quote ค้างอยู่ |
แนวทางแก้ไข
- ใช้ CsvHelper - จัดการ edge cases ครบถ้วน รองรับ mapping ไป class ได้
- ใช้ TextFieldParser (Microsoft.VisualBasic.FileIO) - built-in parser ที่จัดการ CSV ได้ถูกต้อง
- เขียน parser เอง - เฉพาะ CSV เรียบง่าย ไม่มี quote/comma ให้น่าจะทำได้
ตัวอย่างใช้ TextFieldParser (Built-in)
using System;
using Microsoft.VisualBasic.FileIO; // ต้องเพิ่ม reference
class Program
{
public static void Main()
{
using (var parser = new TextFieldParser(@"data.csv"))
{
parser.TextFieldType = FieldType.Delimited;
parser.SetDelimiters(",");
while (!parser.EndOfData)
{
string[] fields = parser.ReadFields();
foreach (var field in fields)
{
Console.Write($"{field} | ");
}
Console.WriteLine();
}
}
}
}