天天看點

ini (ini-parser)配置檔案解析 for donet

介紹

此ini解析庫适用于mono(unity3d),donet,大小在30kb左右。

開源免費:https://github.com/rickyah/ini-parser

使用示例

engine_config.ini  配置檔案内容如下

[Engine]
: product real path
ProductRelPath    = ../Product    
AssetBundleBuildRelPath    = ../Product/Bundles    
StreamingBundlesFolderName = Bundles    
AssetBundleExt = .bytes    
IsLoadAssetBundle = 1      

使用方法如下

using System;
using IniParser.Model;
using IniParser.Model.Formatting;
using IniParser.Parser;

public class EngineConfigs
{
    private readonly IniData _iniData;

    public EngineConfigs(string iniconfig)
    {
        var parser = new IniDataParser();
        _iniData = parser.Parse(iniconfig);
    }

    /// <summary>
    /// GetConfig from section
    /// </summary>
    /// <param name="section"></param>
    /// <param name="key"></param>
    /// <param name="throwError">whether or not throw error when get no config</param>
    /// <returns></returns>
    public string GetConfig(string section, string key, bool throwError = true)
    {
        var sectionData = _iniData[section];
        if (sectionData == null)
        {
            if (throwError)
                throw new Exception("Not found section from ini config: " + section);
            return null;
        }
        var value = sectionData[key];
        if (value == null)
        {
            if (throwError)
                throw new Exception(string.Format("Not found section:`{0}`, key:`{1}` config", section, key));
        }
        return value;
    }
}


public class IniParseDemo
{
    public void Main()
    {
        EngineConfigs engineConfigs = new EngineConfigs("xxx");
        //此處傳回 ../Product    
        var productRelPath = engineConfigs.GetConfig("Engine", "ProductRelPath");
    }
}      

注意事項

IniDataParser.Parse(iniconfig);

iniconfig是具體的内容,而不是某個ini檔案

ini