본문 바로가기
C#/C# 학습 (TIL)

C# CSVReader for Unity

by jjiing 2023. 2. 27.

유니티에서 작업하다보면 CSV 파일을 읽어와야 할 때가 종종 있는데, 

CSVReader를 구글링해서 긁어와 적용시켰다.

 

아래 내용은 내가 적용한 코드와 관련 설명이다.

using System.Collections.Generic;
using System.Text.RegularExpressions;

public class CSVReader 
    {
        static string SPLIT_RE = @",(?=(?:[^""]*""[^""]*"")*(?![^""]*""))";
        static string LINE_SPLIT_RE = @"\r\n|\n\r|\n|\r";
        static char[] TRIM_CHARS = { '\"' };

        public static List<Dictionary<string, object>> Read(string path, string file)
        {
            var list = new List<Dictionary<string, object>>();
			
            //파일 불러오기
            var textAsset = NCommon.NUtil.FileUtils.FileReadText(path, file + ".csv");	//통짜 string 형태
            if (textAsset.IsNullOrEmpty() == true)
                return null;
            var lines = Regex.Split(textAsset, LINE_SPLIT_RE);	//열별로 나눠져서 string[]으로 저장
            
            if (lines.Length <= 1) return list;

            var header = Regex.Split(lines[0], SPLIT_RE);	//첫번째 열을 컬럼명으로 따로 저장
            for (var i = 1; i < lines.Length; i++)			//첫번째 열을 제외한 2번째 열부터 data로 저장
            {

                var values = Regex.Split(lines[i], SPLIT_RE);	//해당 열을 컬럼 별로 구분
                if (values.Length == 0 || values[0] == "") continue;

                var entry = new Dictionary<string, object>();	//원하는 형태로 저장
                for (var j = 0; j < header.Length && j < values.Length; j++)
                {
                    string value = values[j];
                    value = value.TrimStart(TRIM_CHARS).TrimEnd(TRIM_CHARS).Replace("\\", "");
                    object finalvalue = value;
                    int n;
                    float f;
                    if (int.TryParse(value, out n))
                    {
                        finalvalue = n;
                    }
                    else if (float.TryParse(value, out f))
                    {
                        finalvalue = f;
                    }
                    entry[header[j]] = finalvalue;		//최종적으로는 저장되는 dictionary 형태
                }
                list.Add(entry);
            }
            return list;
        }
    }

 

 

이 CSV 리더는

CSV 파일을 긁어와 List<Dictionary<string, Object>> 의 형태로 저장해준다.

나의 경우 이런 Table 명과 Column명을 가져오는 데이터를 긁어와야 했다.

첫번째 열이 컬럼명에 해당한다.

이 경우 결과는

이와 같이 긁어와진다.

즉 [1번컬럼명, 1열 1번컬럼 data] , [2번 컬럼명, 1열 2번 컬럼 data] dictionary 형태로 저장된다. 

주의해야할 점은 data는 범용성을 위해 object 형태로 박싱되어 저장되니 사용할 때 형변환이 필요하다는 것이다.

 

 

 

'C# > C# 학습 (TIL)' 카테고리의 다른 글

유니티 스크롤뷰 초기 설정 에러 기록  (0) 2023.04.24
Enum flag  (0) 2023.02.06
유니티 RectTransform  (0) 2023.01.24
유니티 그래픽스 퍼포먼스 최적화 관련 - 드로우콜  (0) 2022.12.30
유니티 safe Area 대응  (1) 2022.12.12