C#操作ini文件



在C#中,没有内置的INI文件处理功能。然而,你可以通过使用System.IO命名空间中的类来手动读取和写入INI文件。

以下是一个简单的示例,展示了如何读取和写入INI文件:

using System;  
using System.IO;  
  
public class IniFile  
{  
    private string filePath;  
  
    public IniFile(string filePath)  
    {  
        this.filePath = filePath;  
    }  
  
    public string Read(string section, string key, string defaultValue)  
    {  
        string value = defaultValue;  
        try  
        {  
            using (StreamReader sr = new StreamReader(filePath))  
            {  
                string line;  
                while ((line = sr.ReadLine()) != null)  
                {  
                    if (line.StartsWith(section + "="))  
                    {  
                        value = line.Substring(section.Length + 1);  
                        break;  
                    }  
                }  
            }  
        }  
        catch (Exception e)  
        {  
            Console.WriteLine("Error reading ini file: " + e.Message);  
        }  
        return value;  
    }  
  
    public void Write(string section, string key, string value)  
    {  
        try  
        {  
            // 创建新的INI文件内容或清空现有的INI文件内容  
            string[] iniContent = new string[] { section + "=" + value };  
            using (StreamWriter sw = new StreamWriter(filePath))  
            {  
                foreach (string line in iniContent)  
                {  
                    sw.WriteLine(line);  
                }  
            }  
        }  
        catch (Exception e)  
        {  
            Console.WriteLine("Error writing ini file: " + e.Message);  
        }  
    }  
}

使用上述IniFile类的方法:

读取INI文件中的值:

IniFile ini = new IniFile("path/to/your/ini/file.ini");  
string value = ini.Read("sectionName", "keyName", "default value"); // 读取sectionName下的keyName的值,若不存在则返回默认值"default value"

写入INI文件中的值:

IniFile ini = new IniFile("path/to/your/ini/file.ini");  
ini.Write("sectionName", "keyName", "newValue"); // 在sectionName下写入keyName和其对应的值"newValue"