Unity读取配置文件

config.ini存放在Assets目录下,项目打包之后存放在Data目录下

// 从配置文件读取
        string configFile = Application.dataPath + "/config.ini";
        if (File.Exists(configFile))
        {
            ConfigIni ini = new ConfigIni(configFile);
            host = ini.ReadIniContent("DeepStreamServer", "host");
            port = ini.ReadIniContent("DeepStreamServer", "port");
        }
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using UnityEngine;

/// <summary>
/// 读取ini配置文件
/// [Time] 
/// time=10 
/// [Speed] 
/// speed=5 
/// ConfigIni ini=new ConfigIni(Application.StreamingAssets+"/Setting.ini"); 
/// time=ini.ReadIniContent("Time","time");
/// speed=ini.ReadIniContent("Speed","speed");
/// ini.WritePrivateProfileString("Count","count","5");
/// </summary>
public class ConfigIni {

    public string path;

    //ini文件的路径  
    public ConfigIni(string path)
    {
        this.path = path;
    }

    [DllImport("kernel32")]
    public static extern long WritePrivateProfileString(string section, string key, string value, string path);
    [DllImport("kernel32")]
    public static extern int GetPrivateProfileString(string section, string key, string deval, StringBuilder stringBuilder, int size, string path);

    //写入ini文件
    public void WriteIniContent(string section, string key, string value)
    {
        WritePrivateProfileString(section, key, value, this.path);
    }
    //读取Ini文件
    public string ReadIniContent(string section, string key)
    {
        StringBuilder temp = new StringBuilder(255);
        int i = GetPrivateProfileString(section, key, "", temp, 255, this.path);
        return temp.ToString();
    }
    //判断路径是否正确
    public bool IsIniPath()
    {
        return File.Exists(this.path);
    }
}

猜你喜欢

转载自www.cnblogs.com/coolbear/p/9262101.html
今日推荐