在运行时修改appSettings,而不写入磁盘



这是一个在Windows窗体中使用.NET Framework创建的桌面应用程序。

我想创建一种覆盖app.config的方法->appSettings值。

当项目初始化时,它调用一个函数,该函数从匹配appName的数据库中获取params。

这就是功能:

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而不写入磁盘?

有没有其他方法可以让我做到这一点?

根据我的研究,我找到了两种在运行时修改应用程序设置的方法。

首先,您可以使用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;。代码:

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");

最后但同样重要的是,您可以参考如何强制我的.NET应用程序以管理员身份运行?了解如何解决用户权限问题。

相关内容

最新更新