Simplest possible key/value pair file parsing in .NET

前端 未结 5 1720
闹比i
闹比i 2021-01-17 19:07

My project requires a file where I will store key/value pair data that should be able to be read and modified by the user. I want the program to just expect the keys to be t

5条回答
  •  走了就别回头了
    2021-01-17 19:20

    If you're looking for a quick easy function and don't want to use .Net app\user config setting files or worry about serialization issues that sometimes occur of time.

    The following static function can load a file formatted like KEY=VALUE.

    public static Dictionary LoadConfig(string settingfile)
    {
        var dic = new Dictionary();
    
        if (File.Exists(settingfile))
        {
            var settingdata = File.ReadAllLines(settingfile);
            for (var i = 0; i < settingdata.Length; i++)
            {
                var setting = settingdata[i];
                var sidx = setting.IndexOf("=");
                if (sidx >= 0)
                {
                    var skey = setting.Substring(0, sidx);
                    var svalue = setting.Substring(sidx+1);
                    if (!dic.ContainsKey(skey))
                    {
                        dic.Add(skey, svalue);
                    }
                }
            }
        }
    
        return dic;
    }
    

    Note: I'm using a Dictionary so keys must be unique, which is usually that case with setting.

    USAGE:

    var settingfile = AssemblyDirectory + "\\mycustom.setting";
    var settingdata = LoadConfig(settingfile);
    if (settingdata.ContainsKey("lastrundate"))
    {
        DateTime lout;
        string svalue;
        if (settingdata.TryGetValue("lastrundate", out svalue))
        {
            DateTime.TryParse(svalue, out lout);
            lastrun = lout;
        }
    }
    

提交回复
热议问题