본문 바로가기
개발/C#

유니티 C# CSV 파일 저장, 불러오기 Read, Write 간단 사용법

by SPNK 2022. 6. 20.
반응형
  • 파일 저장 경로 불러오는 코드 작성
using System.IO;
using UnityEngine;

public static class SystemPath
{
    public static string GetPath(string fileName)
    {
        string path = GetPath();
        return Path.Combine(GetPath(), fileName);
    }

    public static string GetPath()
    {
        string path = null;
        switch (Application.platform)
        {
            case RuntimePlatform.Android:
                path = Application.persistentDataPath;
                path = path.Substring(0, path.LastIndexOf('/'));
                return Path.Combine(Application.persistentDataPath, "Resources/");
            case RuntimePlatform.IPhonePlayer:
            case RuntimePlatform.OSXEditor:
            case RuntimePlatform.OSXPlayer:
                path = Application.persistentDataPath;
                path = path.Substring(0, path.LastIndexOf('/'));
                return Path.Combine(path, "Assets", "Resources/");       
            case RuntimePlatform.WindowsEditor:
                path = Application.dataPath;
                path = path.Substring(0, path.LastIndexOf('/'));
                return Path.Combine(path, "Assets", "Resources/");
            default:
                path = Application.dataPath;
                path = path.Substring(0, path.LastIndexOf('/'));
                return Path.Combine(path, "Resources/");
        }
    }
}

 

 

  • CSV Reader 작성
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.IO;

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 file)
    {
        var list = new List<Dictionary<string, object>>();
        string[] lines;

        if (File.Exists(SystemPath.GetPath() + file + ".csv"))
        {
            string source;
            StreamReader sr = new StreamReader(SavePath.GetPath() + file + ".csv");
            source = sr.ReadToEnd();
            sr.Close();

            lines = Regex.Split(source, LINE_SPLIT_RE);

            Debug.Log("Load " + file + ".csv");
        }
        else
        {
            return null;
        }

        if (lines.Length <= 1) return list;

        var header = Regex.Split(lines[0], SPLIT_RE);
        for (var i = 1; i < lines.Length; i++)
        {

            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("\\", "");
                value = value.Replace("<br>", "\n");
                value = value.Replace("<c>", ",");
                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;
            }
            list.Add(entry);
        }
        return list;
    }
}

 

반응형

 

  • CSV 파일 저장하기
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;
using UnityEngine.UI;

public class CSVManager : MonoBehaviour
{
    public string fileName = "Setting.csv";

    public InputField nameText;
    public InputField countryText;
    public InputField yearText;
    public InputField heightText;
    
    List<string[]> data = new List<string[]>();
    string[] tempData;
    
    void Awake()
    {
    	data.Clear();
        
        tempData = new string[4];
        tempData[0] = "Name";
        tempData[1] = "Country";
        tempData[2] = "Year";
        tempData[3] = "Height";
        data.Add(tempData);
	}
    
    public void SaveCSVFile()
    {
    	tempData = new string[4];
        tempData[0] = nameText.text;
        tempData[1] = countryText.text;
        tempData[2] = yearText.text;
        tempData[3] = heightText.text;
        data.Add(tempData);
        
        string[][] output = new string[data.Count][];

        for (int i = 0; i < output.Length; i++)
        {
            output[i] = data[i];
        }

        int length = output.GetLength(0);
        string delimiter = ",";

        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < length; i++)
        {
            sb.AppendLine(string.Join(delimiter, output[i]));
        }

        string filepath = SystemPath.GetPath();

        if (!Directory.Exists(filepath))
        {
            Directory.CreateDirectory(filepath);
        }

        StreamWriter outStream = System.IO.File.CreateText(filepath + fileName);
        outStream.Write(sb);
        outStream.Close();
    }
}

 

 

  • CSV 파일 불러오기
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;
using UnityEngine.UI;

public class CSVManager : MonoBehaviour
{
    public string fileName = "Setting";

    public InputField nameText;
    public InputField countryText;
    public InputField yearText;
    public InputField heightText;
    
    List<Dictionary<string, object>> dicList = new List<Dictionary<string, object>>();
    
    void Awake()
    {

    }
    
    public void LoadCSVFile()
    {
    	dicList.Clear();

        dicList = CSVReader.Read(fileName);

        nameText.text = dicList[0]["Name"].ToString();
        countryText.text = dicList[0]["Country"].ToString();
        yearText.text = dicList[0]["Year"].ToString();
        heightText.text = dicList[0]["Height"].ToString();
    }
}

 


참고할만한 글

 

 

유니티 C# 구글 로그인 Google Play Games 간단 사용법

using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using GooglePlayGames; using GooglePlayGames.BasicApi; public class GooglePlayManager : MonoBehaviour { private void Awake() //구글 로그인 초기화 { PlayGam

parksh3641.tistory.com

 

 

유니티 C# 구글 애드몹 Google Admob 보상형 광고 간단 적용법

구글 애드몹 SDK 설치 https://github.com/googleads/googleads-mobile-unity/releases Releases · googleads/googleads-mobile-unity Official Unity Plugin for the Google Mobile Ads SDK - googleads/googleads-mobile-unity github.com 구글 애드몹 홈페

parksh3641.tistory.com

반응형

댓글