C# 如何解析ini文件
时间: 2024-05-12 22:15:00 浏览: 18
C# 中可以使用 `System.IO` 命名空间下的 `StreamReader` 和 `StreamWriter` 类来读写 ini 文件,也可以使用 `System.Configuration` 命名空间下的 `ConfigurationManager` 类来读取 ini 文件。
以下是使用 `StreamReader` 和 `StreamWriter` 类读写 ini 文件的示例代码:
```csharp
using System.IO;
// 读取 ini 文件
var lines = File.ReadAllLines("config.ini");
foreach (var line in lines)
{
if (line.StartsWith("#")) // 忽略注释
continue;
var parts = line.Split('=');
if (parts.Length != 2) // 忽略格式不正确的行
continue;
var key = parts[0].Trim();
var value = parts[1].Trim();
// TODO: 处理 key 和 value
}
// 写入 ini 文件
using (var sw = new StreamWriter("config.ini"))
{
sw.WriteLine("# This is a config file.");
sw.WriteLine("key1=value1");
sw.WriteLine("key2=value2");
// TODO: 写入更多配置项
}
```
如果你想使用 `ConfigurationManager` 类来读取 ini 文件,需要先在项目的 `app.config` 或 `web.config` 文件中添加配置节:
```xml
<configuration>
<configSections>
<section name="myconfig" type="System.Configuration.NameValueSectionHandler" />
</configSections>
<myconfig>
<add key="key1" value="value1" />
<add key="key2" value="value2" />
<!-- 更多配置项 -->
</myconfig>
</configuration>
```
然后在代码中使用以下代码读取配置项:
```csharp
var config = ConfigurationManager.GetSection("myconfig") as NameValueCollection;
if (config != null)
{
var value = config["key1"]; // 读取 key1 对应的值
// TODO: 处理其他配置项
}
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)