cSharp如何读写INI配置文件
时间: 2024-05-10 09:19:53 浏览: 119
cSharp可以通过System.IO命名空间下的IniFile类快速读写INI配置文件。具体代码实现可以参考以下示例:
```csharp
using System.IO;
public class IniFile {
private string filePath;
public IniFile(string filePath) {
this.filePath = filePath;
}
public string ReadValue(string section, string key) {
var iniValue = "";
if (File.Exists(filePath)) {
using (var sr = new StreamReader(filePath)) {
string line;
while ((line = sr.ReadLine()) != null) {
if (line.Trim().StartsWith(section)) {
while ((line = sr.ReadLine()) != null && !line.Trim().StartsWith("["))
{
var fields = line.Split('=');
if (fields[0].Trim() == key) {
iniValue = fields[1].Trim();
break;
}
}
}
}
}
}
return iniValue;
}
public void WriteValue(string section, string key, string value) {
if (File.Exists(filePath)) {
var sb = new StringBuilder();
var modified = false;
using (var sr = new StreamReader(filePath)) {
string line;
while ((line = sr.ReadLine()) != null) {
if (line.Trim().StartsWith(section)) {
sb.AppendLine(line);
while ((line = sr.ReadLine()) != null && !line.Trim().StartsWith("["))
{
if (line.Trim().StartsWith($"{key}=")) {
sb.AppendLine($"{key}={value}");
modified = true;
}
else {
sb.AppendLine(line);
}
}
}
else {
sb.AppendLine(line);
}
}
}
if (!modified) {
sb.AppendFormat("{0}[{1}]\r\n{2}={3}\r\n", Environment.NewLine, section, key, value);
}
File.WriteAllText(filePath, sb.ToString());
}
}
}
```
使用示例:
```csharp
var iniFile = new IniFile("config.ini");
var value = iniFile.ReadValue("database", "connectionString");
Console.WriteLine("读取配置项 database:connectionString = {0}", value);
iniFile.WriteValue("update", "lastUpdateTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
```
输出结果:
```
读取配置项 database:connectionString = Data Source=127.0.0.1;Initial Catalog=TestDB;User ID=test;Password=123456
```
阅读全文