c#写入ini文件
在C#中,你可以使用System.IO命名空间下的StreamWriter类来写入INI文件。下面是一个简单的示例代码:
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "config.ini";
string section = "Settings";
string key = "Username";
string value = "JohnDoe";
WriteIniKey(filePath, section, key, value);
}
static void WriteIniKey(string filePath, string section, string key, string value)
{
using (StreamWriter writer = new StreamWriter(filePath, true))
{
writer.WriteLine($"[{section}]");
writer.WriteLine($"{key}={value}");
}
}
}
在上面的示例中,我们使用StreamWriter打开INI文件并追加内容。WriteLine方法用于写入INI文件的每一行,通过使用字符串插值来构建每一行的内容。
请注意,上述示例中的filePath变量指定了INI文件的路径。如果文件不存在,StreamWriter会自动创建一个新的文件。
另外,true参数将StreamWriter实例的构造函数设置为追加模式,以便在已有内容的末尾添加新内容。如需覆盖现有文件,请使用false参数或完全删除原始文件。
此外,示例中的section、key和value变量分别表示INI文件中的节、键和值。你可以根据需要修改它们的值。
运行上述代码后,会在指定的路径下创建一个名为config.ini的文件,并在文件中写入以下内容:
[Settings]
Username=JohnDoe
你可以根据需要使用不同的键和值来写入其他配置选项
原文地址: http://www.cveoy.top/t/topic/iYWk 著作权归作者所有。请勿转载和采集!