Reading/writing an INI file

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

    The code in joerage's answer is inspiring.

    Unfortunately, it changes the character casing of the keys and does not handle comments. So I wrote something that should be robust enough to read (only) very dirty INI files and allows to retrieve keys as they are.

    It uses some LINQ, a nested case insensitive string dictionary to store sections, keys and values, and read the file in one go.

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    
    class IniReader
    {
        Dictionary> ini = new Dictionary>(StringComparer.InvariantCultureIgnoreCase);
    
        public IniReader(string file)
        {
            var txt = File.ReadAllText(file);
    
            Dictionary currentSection = new Dictionary(StringComparer.InvariantCultureIgnoreCase);
    
            ini[""] = currentSection;
    
            foreach(var line in txt.Split(new[]{"\n"}, StringSplitOptions.RemoveEmptyEntries)
                                   .Where(t => !string.IsNullOrWhiteSpace(t))
                                   .Select(t => t.Trim()))
            {
                if (line.StartsWith(";"))
                    continue;
    
                if (line.StartsWith("[") && line.EndsWith("]"))
                {
                    currentSection = new Dictionary(StringComparer.InvariantCultureIgnoreCase);
                    ini[line.Substring(1, line.LastIndexOf("]") - 1)] = currentSection;
                    continue;
                }
    
                var idx = line.IndexOf("=");
                if (idx == -1)
                    currentSection[line] = "";
                else
                    currentSection[line.Substring(0, idx)] = line.Substring(idx + 1);
            }
        }
    
        public string GetValue(string key)
        {
            return GetValue(key, "", "");
        }
    
        public string GetValue(string key, string section)
        {
            return GetValue(key, section, "");
        }
    
        public string GetValue(string key, string section, string @default)
        {
            if (!ini.ContainsKey(section))
                return @default;
    
            if (!ini[section].ContainsKey(key))
                return @default;
    
            return ini[section][key];
        }
    
        public string[] GetKeys(string section)
        {
            if (!ini.ContainsKey(section))
                return new string[0];
    
            return ini[section].Keys.ToArray();
        }
    
        public string[] GetSections()
        {
            return ini.Keys.Where(t => t != "").ToArray();
        }
    }
    

提交回复
热议问题