如何通过C#有效的读取 INI 文件?

咨询区

  • zendar

在 .NET 中是否有内置的类可以读取标准的 .ini 文件,文件格式如下:

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

Delphi 中有标准的 TIniFile 组件,我想知道 .NET 中是否有类似的组件 ?.

回答区

  • Scott Chamberlain

如果你的需求仅仅是读 .ini 而不是写,建议使用 ASP.NET Core 中自带的 Microsoft.Extensions.Confiuration.Ini,非常简单,参考如下实现:

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddIniFile("SomeConfig.ini", optional: false);
    Configuration = builder.Build();
}
  • Danny Beckett

其实读写 *.ini 文件不难,我自己实现了一个简单的版本,利用了原始的 P/Invoke 方法,支持所有的 windows 版本。IniFile.cs 代码如下:

using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;

// Change this to match your program's normal namespace
namespace MyProg
{
    class IniFile   // revision 11
    {
        string Path;
        string EXE = Assembly.GetExecutingAssembly().GetName().Name;

        [DllImport("kernel32", CharSet = CharSet.Unicode)]
        static extern long WritePrivateProfileString(string Section, string Key, string Value, string FilePath);

        [DllImport("kernel32", CharSet = CharSet.Unicode)]
        static extern int GetPrivateProfileString(string Section, string Key, string Default, StringBuilder RetVal, int Size, string FilePath);

        public IniFile(string IniPath = null)
        {
            Path = new FileInfo(IniPath ?? EXE + ".ini").FullName;
        }

        public string Read(string Key, string Section = null)
        {
            var RetVal = new StringBuilder(255);
            GetPrivateProfileString(Section ?? EXE, Key, "", RetVal, 255, Path);
            return RetVal.ToString();
        }

        public void Write(string Key, string Value, string Section = null)
        {
            WritePrivateProfileString(Section ?? EXE, Key, Value, Path);
        }

        public void DeleteKey(string Key, string Section = null)
        {
            Write(Key, null, Section ?? EXE);
        }

        public void DeleteSection(string Section = null)
        {
            Write(null, null, Section ?? EXE);
        }

        public bool KeyExists(string Key, string Section = null)
        {
            return Read(Key, Section).Length > 0;
        }
    }
}
  1. 写入操作:
// Or specify a specific name in a specific dir
var MyIni = new IniFile(@"C:\Settings.ini");
MyIni.Write("DefaultVolume", "100");
MyIni.Write("HomePage", "http://www.google.com");

生成的文件如下:

[MyProg]
DefaultVolume=100
HomePage=http://www.google.com
  1. 读取操作:
// Or specify a specific name in a specific dir
var MyIni = new IniFile(@"C:\Settings.ini");
var DefaultVolume = MyIni.Read("DefaultVolume");
var HomePage = MyIni.Read("HomePage");

点评区

现如今大多都是用json替代了xmlini,如果是.NETCore 以上,建议还是用 Confiuration 这种简单粗暴的方式。