csvファイルからデータを取得する

csvファイルからデータを取得するクラス

普通のC#プロダクトの場合

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

public static class ReadCsv
{
    public static IEnumerable<string[]> GetDataArray(string filePath)
    {
        var dataArrayList = new List<string[]>();

        using (var reader = new StreamReader(filePath))
        {
            // 1行目はラベルなので何もしない
            reader.ReadLine();

            while (!reader.EndOfStream)
            {
                var line = reader.ReadLine();

                Debug.Assert(line != null, nameof(line) + " != null");
                
                var elements = line.Split(',').ToArray();
                dataArrayList.Add(elements);
            }
        }

        return dataArrayList;
    }

    public static int GetLabelIndex(string filePath, string labelName)
    {
        using (var reader = new StreamReader(filePath))
        {
            var labelLine = reader.ReadLine();

            Debug.Assert(labelLine != null, nameof(labelLine) + " != null");
            
            var index = labelLine.Split(',').ToList().IndexOf(labelName);

            return index;
        }
    }
}

Unityの場合(Resourcesフォルダを使う)

filePathにはResourcesフォルダ以下のパスを記入する。また.csvのような拡張子は省略する。 例えばAssets/Resources/MasterData/Sample.csvのようなフォルダ構成の場合、 filePathはMasterData/Sampleとなる。

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

public static class ReadCsv
{
    public static IEnumerable<string[]> GetDataArray(string filePath)
    {
        var dataArrayList = new List<string[]>();
        var csvFile = Resources.Load(filePath) as TextAsset;
        Debug.Assert(csvFile != null, nameof(csvFile) + " != null");
        
        using (var reader = new StringReader(csvFile.text))    
        {
            // 1行目はラベルなので何もしない
            reader.ReadLine();

            while (reader.Peek() > -1)
            {
                var line = reader.ReadLine();
                Debug.Assert(line != null, nameof(line) + " != null");
                
                var elements = line.Split(',').ToArray();
                dataArrayList.Add(elements);
            }
        }

        return dataArrayList;
    }

    public static int GetLabelIndex(string filePath, string labelName)
    {
        var csvFile = Resources.Load(filePath) as TextAsset;
        Debug.Assert(csvFile != null, nameof(csvFile) + " != null");
        
        using (var reader = new StringReader(csvFile.text))
        {
            var labelLine = reader.ReadLine();

            Debug.Assert(labelLine != null, nameof(labelLine) + " != null");
            
            var index = labelLine.Split(',').ToList().IndexOf(labelName);

            return index;
        }
    }
}