c# 读写ini文件
时间: 2025-05-13 11:27:46 浏览: 20
C# 中读写 INI 文件可以通过自定义方法或使用第三方库实现。INI 文件是一种常见的配置文件格式,结构简单、易于理解。
以下是通过编写代码手动操作 INI 文件的方式:
### 1. 使用 Windows API 操作 INI 文件
Windows 提供了 `GetPrivateProfileString` 和 `WritePrivateProfileString` 函数来处理 INI 配置文件。可以在 C# 程序中调用这些函数完成对 INI 的读写。
#### 示例代码:
```csharp
using System;
using System.Runtime.InteropServices;
public class IniFileHandler
{
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section, string key, string defaultValue, StringBuilder retval, int size, string filePath);
[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section, string key, string value, string filePath);
public string FilePath { get; set; }
// 构造函数初始化路径
public IniFileHandler(string iniFilePath)
{
this.FilePath = iniFilePath;
}
// 写入值到INI文件
public void WriteValue(string section, string key, string value)
{
WritePrivateProfileString(section, key, value, this.FilePath);
}
// 从INI文件读取指定键的值
public string ReadValue(string section, string key)
{
StringBuilder sb = new StringBuilder(256); // 定义缓冲区大小
int length = GetPrivateProfileString(section, key, "", sb, sb.Capacity, this.FilePath);
return sb.ToString();
}
}
// 测试示例
class Program
{
static void Main()
{
var handler = new IniFileHandler(@"test.ini");
// 写入数据
handler.WriteValue("Section1", "Key1", "Value1");
// 读取数据
string readResult = handler.ReadValue("Section1", "Key1");
Console.WriteLine($"Read Value: {readResult}");
}
}
```
---
### 2. 自己解析字符串内容 (无依赖)
如果不想引入外部依赖项或者系统API,则可以将 `.ini` 视为普通的文本文件,并自行实现逻辑来加载和保存其中的内容。
#### 范例 - 手动读写 INI 文件
```csharp
System.Collections.Specialized.StringCollection settingsInIniFormat =
new System.Collections.Specialized.StringCollection();
settingsInIniFormat.Add("[SectionA]");
settingsInIniFormat.Add("key=value");
...
```
然后逐行分析存储的数据并将其转换回字典形式等更易访问的形式。
阅读全文
相关推荐















