在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對應的值。