.NET框架中是否有可以读写标准.ini文件的类:

[Section]
<keyname>=<value>
...

Delphi有TIniFile组件,我想知道是否有类似的c# ?


当前回答

. net框架的创建者希望您使用基于xml的配置文件,而不是INI文件。所以不,没有内置的机制来读取它们。

不过,也有第三方的解决方案。

INI处理程序可以作为NuGet包获得,例如INI Parser。 您可以编写自己的INI处理程序,这是一种老式的、费力的方法。它为您提供了对实现的更多控制,可以用于坏的方面,也可以用于好的方面。例如,一个INI文件处理类使用c#, P/Invoke和Win32。

其他回答

joerage回答中的代码是鼓舞人心的。

不幸的是,它改变了键的字符大小写,并且不处理注释。所以我写了一些足够健壮的东西,可以读取(只)非常脏的INI文件,并允许按原样检索密钥。

它使用一些LINQ,一个嵌套的不区分大小写的字符串字典来存储节,键和值,并一次性读取文件。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

class IniReader
{
    Dictionary<string, Dictionary<string, string>> ini = new Dictionary<string, Dictionary<string, string>>(StringComparer.InvariantCultureIgnoreCase);

    public IniReader(string file)
    {
        var txt = File.ReadAllText(file);

        Dictionary<string, string> currentSection = new Dictionary<string, string>(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<string, string>(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();
    }
}

下面是我自己的版本,使用正则表达式。这段代码假设每个节名都是唯一的——如果不是这样的话——用List替换Dictionary是有意义的。此函数支持.ini文件注释,从';'字符开始。Section正常启动[Section],键值对也正常出现“key = value”。与节相同的假设-键名是唯一的。

/// <summary>
/// Loads .ini file into dictionary.
/// </summary>
public static Dictionary<String, Dictionary<String, String>> loadIni(String file)
{
    Dictionary<String, Dictionary<String, String>> d = new Dictionary<string, Dictionary<string, string>>();

    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<String, String> lines = new Dictionary<String, String>();

        // 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;
}

CodeProject的这篇文章“一个使用c#的INI文件处理类”应该会有所帮助。

作者创建了一个c#类“Ini”,它公开了KERNEL32.dll中的两个函数。这些函数是:WritePrivateProfileString和GetPrivateProfileString。您需要两个命名空间:System.Runtime.InteropServices和System.Text。

使用Ini类的步骤

在项目名称空间定义中添加

using INI;

像这样创建一个INIFile

INIFile ini = new INIFile("C:\\test.ini");

使用IniWriteValue向section中的特定键写入新值,或使用IniReadValue从特定section中的键读取值。

注意:如果你是从头开始,你可以阅读这篇MSDN文章:如何:将应用程序配置文件添加到c#项目。这是配置应用程序的一种更好的方式。

您应该从xml文件读取和写入数据,因为您可以将整个对象保存到xml,也可以从保存的xml填充对象。它最好是一个易于操作的对象。

以下是如何做到这一点: 将对象数据写入XML文件:https://msdn.microsoft.com/en-us/library/ms172873.aspx 从XML文件中读取对象数据:https://msdn.microsoft.com/en-us/library/ms172872.aspx

INI是一个用于INI文件操作的nuget打包类。它支持读/写,包括注释-写时保留注释。它似乎相当受欢迎,经过测试,易于使用。它也是完全免费和开源的。

免责声明:我是花生酱ini的作者。