【问题标题】:Modify appSettings in runtime without writing to disk在运行时修改 appSettings 而不写入磁盘
【发布时间】:2020-11-14 15:28:26
【问题描述】:

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

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

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

这是函数:

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

我可以使用其他方法来实现这一点吗?

【问题讨论】:

标签: c# visual-studio winforms


【解决方案1】:

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

首先,您可以使用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");

最后一点,您可以参考How do I force my .NET application to run as administrator?了解如何解决用户权限问题。

【讨论】:

    猜你喜欢
    • 2010-10-17
    • 1970-01-01
    • 2016-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多