Reading/writing an INI file

后端 未结 16 2391
南旧
南旧 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 01:02

    Here is my own version, using regular expressions. This code assumes that each section name is unique - if however this is not true - it makes sense to replace Dictionary with List. This function supports .ini file commenting, starting from ';' character. Section starts normally [section], and key value pairs also comes normally "key = value". Same assumption as for sections - key name is unique.

    /// 
    /// Loads .ini file into dictionary.
    /// 
    public static Dictionary> loadIni(String file)
    {
        Dictionary> d = new Dictionary>();
    
        String ini = File.ReadAllText(file);
    
        // Remove comments, preserve linefeeds, if end-user needs to count line number.
        ini = Regex.Replace(ini, @"^\s*;.*$", "", RegexOptions.Multiline);
    
        // Pick up all lines from first section to another section
        foreach (Match m in Regex.Matches(ini, "(^|[\r\n])\\[([^\r\n]*)\\][\r\n]+(.*?)(\\[([^\r\n]*)\\][\r\n]+|$)", RegexOptions.Singleline))
        {
            String sectionName = m.Groups[2].Value;
            Dictionary lines = new Dictionary();
    
            // Pick up "key = value" kind of syntax.
            foreach (Match l in Regex.Matches(ini, @"^\s*(.*?)\s*=\s*(.*?)\s*$", RegexOptions.Multiline))
            {
                String key = l.Groups[1].Value;
                String value = l.Groups[2].Value;
    
                // Open up quotation if any.
                value = Regex.Replace(value, "^\"(.*)\"$", "$1");
    
                if (!lines.ContainsKey(key))
                    lines[key] = value;
            }
    
            if (!d.ContainsKey(sectionName))
                d[sectionName] = lines;
        }
    
        return d;
    }
    

提交回复
热议问题