C# 在运行时修改appSettings而不写入磁盘
这是在Windows窗体中使用.NET Framework创建的桌面应用程序 我想创建一种覆盖app.config->appSettings值的方法 当项目初始化时,它调用一个函数,该函数从匹配appName的数据库中获取参数 这就是功能:C# 在运行时修改appSettings而不写入磁盘,c#,visual-studio,winforms,C#,Visual Studio,Winforms,这是在Windows窗体中使用.NET Framework创建的桌面应用程序 我想创建一种覆盖app.config->appSettings值的方法 当项目初始化时,它调用一个函数,该函数从匹配appName的数据库中获取参数 这就是功能: private void LoadAppConfigs() { var appConfigs = Connection.GetAppConfigs(); Configuration config = Confi
private void LoadAppConfigs()
{
var appConfigs = Connection.GetAppConfigs();
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
foreach (var c in appConfigs)
{
config.AppSettings.Settings[c.Key].Value = c.Value;
}
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection(config.AppSettings.SectionInformation.Name);
}
它可以工作,但这意味着写入磁盘(修改app.config
),这是有问题的,因为用户没有写入磁盘的权限
是否有一种方法可以在运行时修改AppSettings
,而无需写入磁盘
有没有其他方法可以实现这一点?根据我的研究,我发现有两种方法可以在运行时修改appsettings 首先,您可以使用
XmlDocument
来更改它。
详情如下:
XmlDocument xml = new XmlDocument();
string basePath = Directory.GetParent(Environment.CurrentDirectory).Parent.FullName;
string path = basePath + @"\App.config";
xml.Load(path);
XmlNode xNode;
XmlElement xElem1;
XmlElement xElem2;
Configuration cfa = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
xNode = xml.SelectSingleNode("//appSettings");
string AppKey = "Setting2";
string AppValue = "Expensive";
xElem1 = (XmlElement)xNode.SelectSingleNode("//add[@key='" + AppKey + "']");
if (xElem1 != null)
{
xElem1.SetAttribute("value", AppValue);
cfa.AppSettings.Settings[AppKey].Value = AppValue;
}
else
{
xElem2 = xml.CreateElement("add");
xElem2.SetAttribute("key", AppKey);
xElem2.SetAttribute("value", AppValue);
xNode.AppendChild(xElem2);
cfa.AppSettings.Settings.Add(AppKey, AppValue);
}
cfa.Save();
ConfigurationManager.RefreshSection("appSettings");
xml.Save(path);
其次,还可以使用config.AppSettings.Settings[key].Value=Value代码>。
代码:
最后但并非最不重要的一点是,您可以参考了解如何解决用户权限问题。是否必须从应用程序设置本身获取?难道您不能将原始appsettings中的信息存储在类的某个字段中,并在不接触appsettings文件的情况下操作该字段吗?建议config.AppSettings.Set(c.Key,c.Value)代码>。感谢@dxiv对答案进行评论。
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["Setting2"].Value = "Expensive";
config.Save();//exe.config change
string basePath = Directory.GetParent(Environment.CurrentDirectory).Parent.FullName;
string path = basePath + @"\App.config";
config.SaveAs(path);//App.config change
ConfigurationManager.RefreshSection("appSettings");