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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 221,548评论 6 515
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,497评论 3 399
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 167,990评论 0 360
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,618评论 1 296
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,618评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,246评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,819评论 3 421
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,725评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,268评论 1 320
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,356评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,488评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,181评论 5 350
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,862评论 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,331评论 0 24
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,445评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,897评论 3 376
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,500评论 2 359

推荐阅读更多精彩内容

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