unity中 C#从txt文档中读取信息

记录一下:从txt文档中读取信息

//从txt文档中读取信息
//测试:从config.txt文件中读取,读取出数值(100,200)
//存储格式:时间/100
//          总数/200

using System.Collections;
using UnityEngine;
using System.IO;
using System;

public class readInfroTest : MonoBehaviour
{
    //文本中每行的内容
    ArrayList infoall;

    // Start is called before the first frame update
    void Start()
    {
        string pathTemp = "";
        if (Application.platform == RuntimePlatform.Android)
        {
            pathTemp = "/storage/emulated/0/DCIM";   //Android设备目录
        }
        else
        {
            pathTemp = Application.streamingAssetsPath; //streaming 文件夹
            //pathTemp = "D:/storage/emulated/0/DCIM";   //本地测试目录
            //System.Environment.CurrentDirectory //工程目录
        }

        Debug.Log("pathTemp " + pathTemp);
        //得到文本中每一行的内容
        infoall = LoadFile(pathTemp, "config.txt");

        for (int i = 0; i < infoall.Count; i++)
        {
            Debug.Log(infoall[i]);
            Debug.Log(SplitInforStr(infoall[i].ToString()));
            Debug.Log("100 -x = "+  (100 - SplitInforInt(infoall[i].ToString())).ToString());
        }
    }

    /**
     * path:读取文件的路径
     * name:读取文件的名称
     */
    ArrayList LoadFile(string path, string name)
    {
        //使用流的形式读取
        StreamReader sr = null;
        try
        {
            sr = File.OpenText(path + "//" + name);
        }
        catch (Exception e)
        {
            //路径与名称未找到文件则直接返回空
            return null;
        }
        string line;
        ArrayList arrlist = new ArrayList();
        while ((line = sr.ReadLine()) != null)
        {
            //一行一行的读取
            //将每一行的内容存入数组链表容器中
            arrlist.Add(line);
        }

        //关闭流
        sr.Close();
        //销毁流
        sr.Dispose();
        //将数组链表容器返回
        return arrlist;
    }

    /// 
    /// 返回字符串
    /// 
    /// 
    /// 
    string SplitInforStr(string strTemp)
    {
        string[] str = new string[2];
        str = strTemp.Split('/');
        return str[1];
    }

    /// 
    /// 返回int型
    /// 
    /// 
    /// 
    int SplitInforInt(string strTemp)
    {
        string[] str = new string[2];
        str = strTemp.Split('/');

        try
        {//防止读取文失败影响正常运行
            return Convert.ToInt32(str[1]);
        }
        catch (Exception ex)
        {
            Debug.Log(ex);
            return 0;
        }
    }
}

 

你可能感兴趣的:(unity,unity,C#,Android,读取文件,txt)