`using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Reflection;
class Program
{
static void Main()
{
// 获取应用程序的根目录路径
string appDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string configFilePath = Path.Combine(appDirectory, "reg.config");
// 调用方法来创建配置文件
CreateConfigFile(configFilePath);
// 键值对字典
Dictionary<string, string> keyValuePairs = new Dictionary<string, string>
{
{ "key1", "zwNo3bHIOs94h8Gnw0qFoZ6GqX4W0/6AN6soH1gjOjQ=" },
{ "key2", "another_value" },
{ "key3", "yet_another_value" }
};
// 写入多个键值对
WriteKeyValuePairs(configFilePath, keyValuePairs);
// 更新其中一个键值对
UpdateKeyValuePair(configFilePath, "key2", "new_value_for_key2");
}
// 创建配置文件
static void CreateConfigFile(string filePath)
{
if (!File.Exists(filePath))
{
// 创建一个新的配置文件
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.SaveAs(filePath);
Console.WriteLine("配置文件已创建: " + filePath);
}
else
{
Console.WriteLine("配置文件已存在.");
}
}
// 写入多个键值对
static void WriteKeyValuePairs(string filePath, Dictionary<string, string> keyValuePairs)
{
try
{
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
foreach (var pair in keyValuePairs)
{
if (config.AppSettings.Settings[pair.Key] == null)
{
config.AppSettings.Settings.Add(pair.Key, pair.Value);
}
else
{
config.AppSettings.Settings[pair.Key].Value = pair.Value;
}
}
config.Save();
Console.WriteLine("键值对已写入.");
}
catch (Exception ex)
{
Console.WriteLine("写入键值对时出错: " + ex.Message);
}
}
// 更新键值对
static void UpdateKeyValuePair(string filePath, string key, string newValue)
{
try
{
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
if (config.AppSettings.Settings[key] != null)
{
config.AppSettings.Settings[key].Value = newValue;
config.Save();
Console.WriteLine("键值对已更新: " + key + " = " + newValue);
}
else
{
Console.WriteLine("键不存在,无法更新.");
}
}
catch (Exception ex)
{
Console.WriteLine("更新键值对时出错: " + ex.Message);
}
}
}`
标签:Console,string,配置文件,C#,方法,键值,WriteLine,config From: https://www.cnblogs.com/gyl0812/p/18393987