Reading/writing an INI file

后端 未结 16 2412
南旧
南旧 2020-11-22 00:15

Is there any class in the .NET framework that can read/write standard .ini files:

[Section]
=
...

Delphi has th

16条回答
  •  走了就别回头了
    2020-11-22 00:54

    I'm late to join the party, but I had the same issue today and I've written the following implementation:

    using System.Text.RegularExpressions;
    
    static bool match(this string str, string pat, out Match m) =>
        (m = Regex.Match(str, pat, RegexOptions.IgnoreCase)).Success;
    
    static void Main()
    {
        Dictionary> ini = new Dictionary>();
        string section = "";
    
        foreach (string line in File.ReadAllLines(.........)) // read from file
        {
            string ln = (line.Contains('#') ? line.Remove(line.IndexOf('#')) : line).Trim();
    
            if (ln.match(@"^[ \t]*\[(?[\w\-]+)\]", out Match m))
                section = m.Groups["sec"].ToString();
            else if (ln.match(@"^[ \t]*(?[\w\-]+)\=(?.*)", out m))
            {
                if (!ini.ContainsKey(section))
                    ini[section] = new Dictionary();
    
                ini[section][m.Groups["prop"].ToString()] = m.Groups["val"].ToString();
            }
        }
    
    
        // access the ini file as follows:
        string content = ini["section"]["property"];
    }
    

    It must be noted, that this implementation does not handle sections or properties which are not found. To achieve this, you should extend the Dictionary<,>-class to handle unfound keys.


    To serialize an instance of Dictionary> to an .ini-file, I use the following code:

    string targetpath = .........;
    Dictionary> ini = ........;
    StringBuilder sb = new StringBuilder();
    
    foreach (string section in ini.Keys)
    {
        sb.AppendLine($"[{section}]");
    
        foreach (string property in ini[section].Keys)
            sb.AppendLine($"{property}={ini[section][property]");
    }
    
    File.WriteAllText(targetpath, sb.ToString());
    

提交回复
热议问题