C#读取ini文件的方法
时间: 2023-09-09 19:08:40 浏览: 57
在C#中,读取ini文件可以使用System.IO命名空间中的File和StreamReader类来实现。以下是一个基本的示例代码:
```csharp
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
string filePath = "path/to/your/file.ini";
// 检查文件是否存在
if (!File.Exists(filePath))
{
Console.WriteLine("文件不存在!");
return;
}
// 读取ini文件内容
try
{
using (StreamReader reader = new StreamReader(filePath))
{
string line;
while ((line = reader.ReadLine()) != null)
{
// 处理每一行的内容
// 假设每一行是key=value的格式
string[] parts = line.Split('=');
if (parts.Length == 2)
{
string key = parts[0].Trim();
string value = parts[1].Trim();
// 打印key和value
Console.WriteLine("Key: " + key);
Console.WriteLine("Value: " + value);
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("读取文件时发生错误: " + ex.Message);
}
}
}
```
请注意,以上代码假设ini文件的每一行都是以"key=value"的格式,并且没有注释。你需要根据你的实际ini文件格式进行相应的修改。