C#でCSVのエンコードを自動判定して読み込む

.NET Core 3.0以降、Shift-JISエンコーディング(コードページ932)はデフォルトでサポートされなくなりました。そのため、カスタムエンコーディングプロバイダーを登録する必要があります。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

class Program
{
    static void Main()
    {
        string csvFilePath = "your_csv_file.csv";

        // カスタムエンコーディングプロバイダーを登録
        Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

        // ファイルのエンコーディングを判断する
        Encoding encoding = GetFileEncoding(csvFilePath);

        // CSVファイルを読み込む
        var lines = File.ReadAllLines(csvFilePath, encoding).Skip(1); // ヘッダーをスキップ

        foreach (var line in lines)
        {
            var values = line.Split(',');
            string code = values[0].Trim();
            string name = values[1].Trim();
            string market = values[2].Trim();
            string type = values[3].Trim();

            // ここでcode、name、market、typeを使用できます
        }
    }

    static Encoding GetFileEncoding(string filePath)
    {
        // ファイルの先頭からバイトを読み取り、エンコーディングを判断する
        byte[] bom = new byte[4];
        using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
        {
            fileStream.Read(bom, 0, 4);
        }

        if (bom[0] == 0xEF && bom[1] == 0xBB && bom[2] == 0xBF)
        {
            return Encoding.UTF8;
        }
        else if (bom[0] == 0xFF && bom[1] == 0xFE)
        {
            return Encoding.Unicode; // UTF-16 LE
        }
        else if (bom[0] == 0xFE && bom[1] == 0xFF)
        {
            return Encoding.BigEndianUnicode; // UTF-16 BE
        }
        else
        {
            return Encoding.GetEncoding(932); // Shift-JIS
        }
    }
}