Reading/writing an INI file

后端 未结 16 2597
南旧
南旧 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:46

    Try this method:

    public static Dictionary ParseIniDataWithSections(string[] iniData)
    {
        var dict = new Dictionary();
        var rows = iniData.Where(t => 
            !String.IsNullOrEmpty(t.Trim()) && !t.StartsWith(";") && (t.Contains('[') || t.Contains('=')));
        if (rows == null || rows.Count() == 0) return dict;
        string section = "";
        foreach (string row in rows)
        {
            string rw = row.TrimStart();
            if (rw.StartsWith("["))
                section = rw.TrimStart('[').TrimEnd(']');
            else
            {
                int index = rw.IndexOf('=');
                dict[section + "-" + rw.Substring(0, index).Trim()] = rw.Substring(index+1).Trim().Trim('"');
            }
        }
        return dict;
    }
    

    It creates the dictionary where the key is "-". You can load it like this:

    var dict = ParseIniDataWithSections(File.ReadAllLines(fileName));
    

提交回复
热议问题