How to modify the ini configuration file in C#?

In C#, you can modify INI configuration files by using classes from the System.IO namespace. Below is a simple example code:

using System;
using System.IO;
using System.Text;

class Program
{
    static void Main()
    {
        string filePath = "config.ini";
        string key = "key1";
        string value = "value1";

        // 读取INI配置文件
        string[] lines = File.ReadAllLines(filePath);
        StringBuilder newFileContent = new StringBuilder();

        bool keyFound = false;
        foreach (var line in lines)
        {
            if (line.StartsWith(key + "="))
            {
                newFileContent.Append($"{key}={value}\n");
                keyFound = true;
            }
            else
            {
                newFileContent.Append(line + "\n");
            }
        }

        // 如果配置文件中不存在该键,则添加到最后
        if (!keyFound)
        {
            newFileContent.Append($"{key}={value}\n");
        }

        // 将更新后的内容写回到INI配置文件
        File.WriteAllText(filePath, newFileContent.ToString());
    }
}

The code above first reads the content of the INI configuration file, then checks if the key to be modified exists. If it does, it replaces its value; if it doesn’t, it adds a new key-value pair. Finally, it writes the updated content back to the INI configuration file. Please modify the code according to your actual needs.

Leave a Reply 0

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


广告
Closing in 10 seconds
bannerAds