unity 读取INI文件

方法一:System.Runtime.InteropServices

首先得创建一个读取ini配置文件的基类,创建好一个后,后面项目需要都可以直接拿来用了
创建基类得引用命名空间 System.Runtime.InteropServices
下面为基类代码

public class MyIni
{
  public string path;//ini文件的路径
  public MyIni(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);
}
}

函数的使用,得先创建一个txt文本文件然后写入内容
内容格式为大标题“[]”,对应大标题下的内容 “名字(相当于key值)=value(使用中文的话可能会有问题,需要转码,中文的话一般使用xml文档)”

[Time] 
time=10 
[Speed] 
speed=5 

类似这样的写法,然后保存为ini文件,拖拽到项目中StreamingAssets位置,一般都是放在这个路径

下面是函数的调用

public class IniDemo
{
    MyIni ini;

    private int  time=0;
    private float speed=0;
    void Start()
    {
      //获取ini文件
      ini=new MyIni(Application.StreamingAssets+"/Setting.ini");
      //获取Ini文件Time类型下的time对应的数值
      time=ini.ReadIniContent("Time","time");
      speed=ini.ReadIniContent("Speed","speed");
      //写入Count类型count值对应的数值(如果存在了相同的key会覆盖原来key的内容)
      ini.WritePrivateProfileString("Count","count","5");
    }
}

基本上一个简单的ini配置文件的使用就OK了,当然你喜欢的话还可以对基类就行添加函数,添加对一整个大类型直接读取,这都是可以的,不过基本上也够用了。

方法二:INIParser

这个库可处理ini文件。 请注意,该文件可以是任何扩展名(如.txt)只要 文件内容是正确格式。

[Player]  
name=Arnold  
avatar=2  
; This section stored hi-scores  
[Hi-score]  
Top1=32900  
Top2=12000  
Top3=4700  

那怎么使用这个库呢?

  1. 添加 “INIParser.cs” 到 Unity.
  2. 声明一个 INIParser 对象并使用它.
INIParser ini = new INIParser();  
ini.Open(“C:/Test.ini”);  
ini.WriteValue(“Player”,“Name”,“Arnold”);  
ini.Close();  

多个Ini文件时
请注意,对于每个INIParser实例,你在任何一个时间只能有一个open的ini文件,你可以打开下一个ini文件,但是之前您必须使用Close()。

INIParser ini = new INIParser();  
ini.Open(“C:/Test.ini”);  
ini.WriteValue(“Player”,“Name”,“Arnold”);  
ini.WriteValue(“Hi-score”,“Top3”,1000);  
ini.Close();  
ini.Open(“C:/Test2.ini”);  
ini.WriteValue(“Position”,“x”,2);  
ini.WriteValue(“Position”,“y”,3);  
ini.Close();  

Methods方法

Open(string path)

Open ini_file关于 reading 和 writing. 如果这个文件不存在将被创建。. 一旦你完成了reading/writing 记得调用函数 Close( )。来保存这个ini文件的所有改变。

Open(TextAsset asset)

Open 一个 TextAsset 作为 ini_file. 如果做了任何更改,则副本将保存在Persistent Data Path持久性数据的路径下。这个函数会一直看着Persistent Data Path持久数据路径,如果有任何修改的TextAsset的副本,实际上看游戏中的文本资源包之前首先看到在Persistent Data Path持久数据路径的变化。

OpenFromString(string str)

从字符串创建ini文件和打开它用于进行读/写。正确格式化的字符串作为ini文件(即:sections部分,keys键和values值) 否则将无法正确创建ini文件。注意,这个ini文件是暂时的,只存在于内存中。但是你可以使用ToString()返回的字符串可以被保存到服务器或磁盘的完整的ini文件。

string ToString(string str)

返回完整的 ini file 字符串。

Close()

一旦你完成读取或写入任何打开的ini文件,应调用此方法。ini文件数据存储在内存中,直到调用此方法,这一数据被写入到磁盘。

string ReadValue(string section, string key, string default)

(重载: bool, int, long, double, byte[], DateTime)
从ini_file中读取值。 如果值不存在,(默认值)将被返回。

WriteValue(string section, string key, string value)

(overload: bool, int, long, double, byte[], DateTime)
写入 一个值到 ini_file

SectionDelete(string section)

删除整个ini文件的section部分,这也将删除与之关联的所有键/值对。

bool IsSectionExists(string section)

检查是否存在ini文件中的section 节。您不需要检查,以防止错误,因为如果你ReadValue从一个不存在的section 节,ReadValue将只返回默认值。然而,有时它可以是有用的如果ini文件已保存的具体数据。

KeyDelete(string section, string key)

删除被选择的 key (还有和它相关的 value) 从 ini file.中
bool IsKeyExists(string section, string key)
检查以查看是否有指定的键存在于ini文件。您不需要检查,以防止错误,因为如果你ReadValue一个不存在的节,ReadValue将只返回默认值。然而,有时它可以是有用的如果ini文件已保存的具体数据。

Open(TextAsset asset)

TextAsset 是read-only, 所以任何的修改是放在sandbox area 沙箱区域(persistentDataPath).

INIParser ini = new INIParser();  
TextAsset asset = Resource.Load("TextAssetExample") as TextAsset;  
ini.Open(asset);  
ini.WriteValue("Player","Name","Arnold");  
ini.Close();  

有时候,你会想使用TextAsset文本资源作为ini文件。游戏包中包含TextAsset文本资源,因此它在每个平台上的读/写操作可靠。如果你使用streaming assets流的资产作为ini文件,有时你会达到以读/写权限错误移动平台上。
你必须确保该TextAsset文本资源存在,否则任何读/写操作将不会正确工作。
Credits
library 是由STA INIFile改编而成,仿照游戏制作室INI文件系统。

Save 和 load game data

INIParser ini = new INIParser();  
// Open the save file. If the save file does not exist, INIParser automatically create  
// one  
ini.Open(Application.persistentDataPath + "save.txt");  
// Read the score. If the section/key does not exist, default score to 10  
int score = ini.ReadValue("Player","Score",10);  
score += 100;  
ini.WriteValue("Player","Score",score);  
ini.Close();  

在这场比赛第一次运行时,会发生什么?
这段代码从保存文件读取比分,增加100,并保存新的得分值。
Open()将检测到“save.txt”不存在,所以空白“save.txt”将被创建。 然后,分数将被读取。自从“save.txt”是空白的,分数不能在ini文件中找到,所以它默认为10。然后,新的分数的值写入ini文件。

Save 和 load game data 从 TextAsset文件中

INIParser ini = new INIParser();  
TextAsset asset = Resource.Load("TextAssetExample") as TextAsset;  
ini.Open(asset);  
int score = ini.ReadValue("Player","Score",10);  
score += 100;  
ini.WriteValue("Player","Score",score);  
ini.Close();  

有时候,你会想使用TextAsset文本资源作为ini文件。游戏包中包含TextAsset文本资源,因此它在每个平台上的读/写操作可靠。如果你使用streaming assets流的资产作为ini文件,有时你会达到以读/写权限错误移动平台上。
你必须确保该TextAsset文本资源存在,否则任何读/写操作将不会正确工作。

方法三:StreamReader

using UnityEngine;
using System.IO;
using System.Collections.Generic;
/// <summary>
/// unity中对ini配置文件的操作
/// </summary>
public class IniFile
{
    //去掉一行信息的开始和末尾不需要的信息
    private static readonly char[] TrimStart = new char[] { ' ', '\t' };
    private static readonly char[] TrimEnd = new char[] { ' ', '\t', '\r', '\n' };
    //key和value的分隔符
    private const string DELEMITER = "=";
    //路径
    private string strFilePath = null;
    //是否区分大小写
    private bool IsCaseSensitive = false;
    private Dictionary<string, Dictionary<string, string>> IniConfigDic = new Dictionary<string, Dictionary<string, string>>();
    //初始化
    public IniFile(string path, bool isCaseSensitive = false)
    {
        strFilePath = path;
        IsCaseSensitive = isCaseSensitive;
    }
    //解析ini
    public void ParseIni()
    {
        if (!File.Exists(strFilePath))
        {
            Debug.LogWarning("the ini file's path is error:" + strFilePath);
            return;
        }
        using (StreamReader reader = new StreamReader(strFilePath))
        {
            string section = null;  
            string key = null;
            string val = null;  
            Dictionary<string, string> config = null;

            string strLine = null;  
            while ((strLine = reader.ReadLine()) != null)
            {
                strLine = strLine.TrimStart(TrimStart);
                strLine = strLine.TrimEnd(TrimEnd);
                //'#'开始代表注释
                if (strLine.StartsWith("#"))
                {
                    continue;
                }

                if (TryParseSection(strLine, out section))
                {
                    if (!IniConfigDic.ContainsKey(section))
                    {
                        IniConfigDic.Add(section, new Dictionary<string, string>());
                    }
                    config = IniConfigDic[section];
                }
                else
                {
                    if (config != null)
                    {
                        if (TryParseConfig(strLine, out key, out val))
                        {
                            if (config.ContainsKey(key))
                            {
                                config[key] = val;
                                Debug.LogWarning("the Key[" + key + "] is appear repeat");
                            }
                            else
                            {
                                config.Add(key, val);
                            }
                        }
                    }
                    else
                    {
                        Debug.LogWarning("the ini file's format is error,lost [Section]'s information");
                    }
                }
            }
        }
    }
    //写入ini
    public void SaveIni()
    {
        if (string.IsNullOrEmpty(strFilePath))
        {
            Debug.LogWarning("Empty file name for SaveIni.");
            return;
        }

        string dirName = Path.GetDirectoryName(strFilePath);
        if (string.IsNullOrEmpty(dirName))
        {
            Debug.LogWarning(string.Format("Empty directory for SaveIni:{0}.", strFilePath));
            return;
        }
        if (!Directory.Exists(dirName))
        {
            Directory.CreateDirectory(dirName);
        }

        using (StreamWriter sw = new StreamWriter(strFilePath))
        {
            foreach (KeyValuePair<string, Dictionary<string, string>> pair in IniConfigDic)
            {
                sw.WriteLine("[" + pair.Key + "]");
                foreach (KeyValuePair<string, string> cfg in pair.Value)
                {
                    sw.WriteLine(cfg.Key + DELEMITER + cfg.Value);
                }
            }
        }
    }

    public string GetString(string section, string key, string defaultVal)
    {
        if (!IsCaseSensitive)
        {
            section = section.ToUpper();
            key = key.ToUpper();
        }
        Dictionary<string, string> config = null;
        if (IniConfigDic.TryGetValue(section, out config))
        {
            string ret = null;
            if (config.TryGetValue(key, out ret))
            {
                return ret;
            }
        }
        return defaultVal;
    }

    public int GetInt(string section, string key, int defaultVal)
    {
        string val = GetString(section, key, null);
        if (val != null)
        {
            return int.Parse(val);
        }
        return defaultVal;
    }

    public void SetString(string section, string key, string val)
    {
        if (!string.IsNullOrEmpty(section) && !string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(val))
        {
            if (!IsCaseSensitive)
            {
                section = section.ToUpper();
                key = key.ToUpper();
            }
            Dictionary<string, string> config = null;
            if (!IniConfigDic.TryGetValue(section, out config))
            {
                config = new Dictionary<string, string>();
                IniConfigDic[section] = config;
            }
            config[key] = val;
        }
    }

    public void SetInt(string section, string key, int val)
    {
        SetString(section, key, val.ToString());
    }

    public void AddString(string section, string key, string val)
    {
        if (!string.IsNullOrEmpty(section) && !string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(val))
        {
            if (!IsCaseSensitive)
            {
                section = section.ToUpper();
                key = key.ToUpper();
            }
            Dictionary<string, string> config = null;
            if (!IniConfigDic.TryGetValue(section, out config))
            {
                config = new Dictionary<string, string>();
                IniConfigDic[section] = config;
            }
            if (!config.ContainsKey(key))
            {
                config.Add(key, val);
            }
        }
    }

    public void AddInt(string section, string key, int val)
    {
        AddString(section, key, val.ToString());
    }

    public bool RemoveSection(string section)
    {
        if (IniConfigDic.ContainsKey(section))
        {
            IniConfigDic.Remove(section);
            return true;
        }
        return false;
    }

    public bool RemoveConfig(string section, string key)
    {
        if (!IsCaseSensitive)
        {
            section = section.ToUpper();
            key = key.ToUpper();
        }
        Dictionary<string, string> config = null;
        if (IniConfigDic.TryGetValue(section, out config))
        {
            if (config.ContainsKey(key))
            {
                config.Remove(key);
                return true;
            }
        }
        return false;
    }

    public Dictionary<string, string> GetSectionInfo(string section)
    {
        Dictionary<string, string> res = null;
        if (!IsCaseSensitive)
        {
            section = section.ToUpper();
        }
        IniConfigDic.TryGetValue(section, out res);
        return res;
    }

    private bool TryParseSection(string strLine, out string section)
    {
        section = null;
        if (!string.IsNullOrEmpty(strLine))
        {
            int len = strLine.Length;
            if (strLine[0] == '[' && strLine[len - 1] == ']')
            {
                section = strLine.Substring(1, len - 2);
                if (!IsCaseSensitive)
                {
                    section = section.ToUpper();
                }
                return true;
            }
        }
        return false;
    }

    private bool TryParseConfig(string strLine, out string key, out string val)
    {
        if (strLine != null && strLine.Length >= 3)
        {
            string[] contents = strLine.Split(DELEMITER.ToCharArray());
            if (contents.Length == 2)
            {
                key = contents[0].TrimStart(TrimStart);
                key = key.TrimEnd(TrimEnd);
                val = contents[1].TrimStart(TrimStart);
                val = val.TrimEnd(TrimEnd);
                if (key.Length > 0 && val.Length > 0)
                {
                    if (!IsCaseSensitive)
                    {
                        key = key.ToUpper();
                    }

                    return true;
                }
            }
        }

        key = null;
        val = null;
        return false;
    }
}

引用文章出处:http://blog.csdn.net/u010019717/article/details/42614099
http://blog.csdn.net/husheng0/article/details/52834564

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 132,356评论 18 139
  • ¥开启¥ 【iAPP实现进入界面执行逐一显】 〖2017-08-25 15:22:14〗 《//首先开一个线程,因...
    小菜c阅读 5,619评论 0 17
  • 1.创建文件夹 !/bin/sh mkdir -m 777 "%%1" 2.创建文件 !/bin/sh touch...
    BigJeffWang阅读 9,145评论 3 53
  • 人民币对美元汇率持续下跌,已经突破6.9关口,股市仅剩的一些散户也纷纷撤出资本去换美元,部分国人开始取消年底的出境...
    壹声阅读 194评论 3 5
  • 我醒来的时候已经是早上了,第一件事情就是看手机有没有人给我发消息。我一边找纸擦鼻涕,一边看手机。 我发现有人给我发...
    爱梦的我阅读 154评论 0 0