Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Đọc file CSV và lưu vào mảng trong C#

Đọc file CSV (Comma-Separated Values) bằng StreamReader và parse từng dòng. Lưu ý: CSV thực tế có thể chứa dấu phẩy trong field (cần quote), xuống dòng trong field -> nên dùng thư viện chuyên dụng (CsvHelper, Sylvan.Data.Csv).

Cách đơn giản (Split cơ bản - Chỉ cho CSV đơn giản)


using System;
using System.Collections.Generic;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = @"C:\Data\data.csv";
        var allValues = new List();
        
        if (File.Exists(filePath))
        {
            using (var reader = new StreamReader(filePath))
            {
                while (!reader.EndOfStream)
                {
                    string line = reader.ReadLine();
                    if (string.IsNullOrWhiteSpace(line)) continue;
                    
                    string[] values = line.Split(',');
                    foreach (string val in values)
                        allValues.Add(val.Trim());
                }
            }
        }
        
        foreach (var v in allValues) Console.WriteLine(v);
        Console.ReadLine();
    }
}

File CSV mẫu (Data.csv)


A,B,C
1,2,3
Hello,World,Test

Kết quả


A
B
C
1
2
3
Hello
World
Test

Cách nâng cao: Dùng CsvHelper (Khuyến nghị cho production)


// NuGet: CsvHelper
using CsvHelper;
using CsvHelper.Configuration;
using System.Globalization;

var config = new CsvConfiguration(CultureInfo.InvariantCulture)
{
    HasHeaderRecord = true,
    MissingFieldFound = null // Ignore missing
};

using var reader = new StreamReader(filePath);
using var csv = new CsvReader(reader, config);

var records = csv.GetRecords(); // Hoặc strongly-typed class

foreach (var record in records)
{
    // record là IDynamicMetaObjectProvider, access property động
    Console.WriteLine($"Col1: {record.Column1}, Col2: {record.Column2}");
}

Strongly-typed với Class


public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string City { get; set; }
}

// CSV: Name,Age,City
// John,30,New York
// Jane,25,"Los Angeles, CA" (có dấu phẩy trong field -> cần quote)

using var csv = new CsvReader(reader, config);
var people = csv.GetRecords().ToList();

foreach (var p in people)
    Console.WriteLine($"{p.Name}, {p.Age}, {p.City}");

Xử lý CSV phức tạp (Quote, Escape, Newline in field)

  • Split(',') KHÔNG xử lý được: "A,B",C -> sai.
  • CsvHelper xử lý chuẩn RFC 4180: quote, escape, newline trong field.
  • Sylvan.Data.Csv (fast, low allocation) - thay thế tốt cho CsvHelper.

Lưu vào mảng 2 chiều (string[][])


var rows = new List();

using (var reader = new StreamReader(filePath))
{
    while (!reader.EndOfStream)
    {
        string line = reader.ReadLine();
        if (!string.IsNullOrWhiteSpace(line))
            rows.Add(line.Split(','));
    }
}

// Truy cập
string firstCell = rows[0][0]; // "A"
string secondRowThirdCol = rows[1][2]; // "3"

Lời khuyên: Với CSV đơn giản, không quote, không newline trong field -> Split OK. Production -> CsvHelper hoặc Sylvan.Data.Csv.