c#中ini配置文件怎么修改

c#
795
2024/3/30 12:47:23
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在C#中修改INI配置文件可以通过使用System.IO命名空间中的类来实现。以下是一个简单的示例代码:

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

以上代码首先读取INI配置文件的内容,然后检查是否存在要修改的键,如果存在则替换其值,如果不存在则添加新的键值对。最后将更新后的内容写回到INI配置文件中。请根据自己的实际需求对代码进行修改。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: c#向上取整的方法是什么