What is the method for reading and writing ini files in C#?

In C#, the StreamReader and StreamWriter classes under the System.IO namespace can be used to read and write INI files. Here is a simple example code:

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);

In the example above, the IniFile class encapsulates methods for reading and writing INI files. The ReadValue method is used to read the value corresponding to a specified section and key, while the WriteValue method is used to write a value corresponding to a specified section and key.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds