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

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

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


当前回答

如果你只是想要一个简单的阅读器没有部分和任何其他dll这里是一个简单的解决方案:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Tool
{
    public class Config
    {
        Dictionary <string, string> values;
        public Config (string path)
        {
            values = File.ReadLines(path)
            .Where(line => (!String.IsNullOrWhiteSpace(line) && !line.StartsWith("#")))
            .Select(line => line.Split(new char[] { '=' }, 2, 0))
            .ToDictionary(parts => parts[0].Trim(), parts => parts.Length>1?parts[1].Trim():null);
        }
        public string Value (string name, string value=null)
        {
            if (values!=null && values.ContainsKey(name))
            {
                return values[name];
            }
            return value;
        }
    }
}

使用示例:

    file = new Tool.Config (Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\config.ini");
    command = file.Value ("command");
    action = file.Value ("action");
    string value;
    //second parameter is default value if no key found with this name
    value = file.Value("debug","true");
    this.debug = (value.ToLower()=="true" || value== "1");
    value = file.Value("plain", "false");
    this.plain = (value.ToLower() == "true" || value == "1");

配置文件内容同时(如你所见,支持#符号的行注释):

#command to run
command = php

#default script
action = index.php

#debug mode
#debug = true

#plain text mode
#plain = false

#icon = favico.ico

其他回答

这是我的班级,效果非常好:

public static class IniFileManager
{


    [DllImport("kernel32")]
    private static extern long WritePrivateProfileString(string section,
        string key, string val, string filePath);
    [DllImport("kernel32")]
    private static extern int GetPrivateProfileString(string section,
             string key, string def, StringBuilder retVal,
        int size, string filePath);
    [DllImport("kernel32.dll")]
    private static extern int GetPrivateProfileSection(string lpAppName,
             byte[] lpszReturnBuffer, int nSize, string lpFileName);


    /// <summary>
    /// Write Data to the INI File
    /// </summary>
    /// <PARAM name="Section"></PARAM>
    /// Section name
    /// <PARAM name="Key"></PARAM>
    /// Key Name
    /// <PARAM name="Value"></PARAM>
    /// Value Name
    public static void IniWriteValue(string sPath,string Section, string Key, string Value)
    {
        WritePrivateProfileString(Section, Key, Value, sPath);
    }

    /// <summary>
    /// Read Data Value From the Ini File
    /// </summary>
    /// <PARAM name="Section"></PARAM>
    /// <PARAM name="Key"></PARAM>
    /// <PARAM name="Path"></PARAM>
    /// <returns></returns>
    public static string IniReadValue(string sPath,string Section, string Key)
    {
        StringBuilder temp = new StringBuilder(255);
        int i = GetPrivateProfileString(Section, Key, "", temp,
                                        255, sPath);
        return temp.ToString();

    }

}

使用是显而易见的,因为它是一个静态类,只需调用IniFileManager。IniWriteValue用于读取section或IniFileManager。IniReadValue用于读取section。

我想介绍一个完全用c#创建的IniParser库,所以它不包含任何操作系统的依赖关系,这使得它与Mono兼容。MIT许可的开源软件——所以它可以在任何代码中使用。

你可以在GitHub中查看源代码,它也可以作为NuGet包使用

它是高度可配置的,使用起来非常简单。

很抱歉我不要脸的插播,但我希望它能对那些重新审视这个答案的人有所帮助。

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#项目。这是配置应用程序的一种更好的方式。

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

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

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

试试这个方法:

public static Dictionary<string, string> ParseIniDataWithSections(string[] iniData)
{
    var dict = new Dictionary<string, string>();
    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;
}

它创建键为“-”的字典。你可以这样加载它:

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