在C#中,可以使用System.Configuration
命名空间下的ConfigurationManager
类来读取config.ini
文件中的数据。但是,config.ini
文件并不是.NET框架默认支持的配置文件格式。你需要使用第三方库,如DotNetConfig
,来处理INI文件。
首先,通过NuGet安装DotNetConfig
库:
Install-Package DotNetConfig
然后,你可以使用以下代码来读取config.ini
文件中的数据:
using System;
using System.Configuration;
using DotNetConfig;
namespace ReadConfigFileExample
{
class Program
{
static void Main(string[] args)
{
// 获取config.ini文件的路径
var configPath = "config.ini";
// 使用DotNetConfig库读取config.ini文件
var config = new IniConfig(configPath);
// 读取section中的数据
if (config.TryGetSection("SectionName", out var section))
{
// 读取key-value对
if (section.TryGetString("KeyName", out var value))
{
Console.WriteLine($"KeyName: {value}");
}
else
{
Console.WriteLine("KeyName not found");
}
}
else
{
Console.WriteLine("SectionName not found");
}
}
}
}
在这个例子中,我们首先获取config.ini
文件的路径,然后使用DotNetConfig
库创建一个IniConfig
对象。接下来,我们尝试获取名为SectionName
的节,并在该节中查找名为KeyName
的键。如果找到了键,我们将其值输出到控制台。