在C#中,可以使用System.IO
命名空间下的StreamReader
和StreamWriter
类来读写INI文件。以下是一个简单的示例代码:
using System;
using System.IO;
public class IniFile
{
private string filePath;
public IniFile(string filePath)
{
this.filePath = filePath;
}
public string ReadValue(string section, string key)
{
string value = "";
using (StreamReader sr = new StreamReader(filePath))
{
string line;
while ((line = sr.ReadLine()) != null)
{
if (line.StartsWith($"[{section}]"))
{
while ((line = sr.ReadLine()) != null)
{
if (line.StartsWith(key))
{
value = line.Split('=')[1].Trim();
break;
}
}
break;
}
}
}
return value;
}
public void WriteValue(string section, string key, string value)
{
bool sectionExists = false;
string tempFile = Path.GetTempFileName();
using (StreamReader sr = new StreamReader(filePath))
using (StreamWriter sw = new StreamWriter(tempFile))
{
string line;
while ((line = sr.ReadLine()) != null)
{
if (line.StartsWith($"[{section}]"))
{
sectionExists = true;
}
sw.WriteLine(line);
}
if (!sectionExists)
{
sw.WriteLine($"[{section}]");
}
sw.WriteLine($"{key}={value}");
}
File.Delete(filePath);
File.Move(tempFile, filePath);
}
}
// 使用示例
IniFile ini = new IniFile("example.ini");
ini.WriteValue("Section1", "Key1", "Value1");
string value = ini.ReadValue("Section1", "Key1");
Console.WriteLine(value);
在以上示例中,IniFile
类封装了读取和写入INI文件的方法。通过ReadValue
方法可以读取指定section和key对应的值,通过WriteValue
方法可以写入指定section和key对应的值。