gpt4 book ai didi

.net - 在运行时或安装时修改 App.config 中的配置部分

转载 作者:行者123 更新时间:2023-12-01 04:40:47 24 4
gpt4 key购买 nike

我有一个使用 Visual Studio 2008 的发布 (ClickOnce) 系统部署的 WinForms 应用程序。在应用程序的 app.config 文件中,我有一个第三方组件需要的配置部分,其形式为:

<section name="thirdPartySection"
type="System.Configuration.NameValueSectionHandler" />

因此该部分不在 appSettings 中,看起来像:

<thirdPartySection >
<add key="someKey" value="someValue" />
</thirdPartySection >

我知道键/值对是一个 NameValueCollection。我面临的问题是,我希望在部署时或运行时更改值(我都可以),以便 someValue 将是 someOtherValue 基于安装的环境。

目前我在运行时进行了一些其他配置更改,但这些更改位于 AppSettings 部分,因此很容易获得。我在寻找解决方案的过程中找到了很多引用资料,但它们似乎依赖于具有自定义类的部分,而不是我遇到的 NameValueCollection。

有谁知道修改这些数据的最佳方法吗?使用 ConfigurationManager.RefreshSection() 进行运行时更改会更符合我当前的代码,但我也愿意在安装阶段接受建议。

编辑:这在运行时有效。这就是我处理旧配置覆盖的方式。

Configuration config = ConfigurationManager.OpenExeConfiguration(
ConfigurationUserLevel.None);

config.AppSettings.Settings["Main.ConnectionString"].Value =
PolicyTrackerInfo.ConnectionString;

config.AppSettings.Settings["Main.linq"].Value =
PolicyTrackerInfo.LinqConnectionString;


config.Save(ConfigurationSaveMode.Modified);

ConfigurationManager.RefreshSection("appSettings");

我尝试对另一个部分做同样的事情:

string overwriteXml = config.GetSection("thirdPartySection")
.SectionInformation.GetRawXml();

XmlDocument xml = new XmlDocument();
xml.LoadXml(overwriteXml);
XmlNode node = xml.SelectSingleNode("thirdPartySection/add");
node.Attributes["value"].Value = PolicyTrackerInfo.OverwriteString;

到目前为止,还不错。但是,我没有看到允许我用修改后的数据替换旧 XML 的方法。 运行时可以吗?

顺便说一句:我尝试手动修改 app.config.deploy 文件。这只是给我一个验证错误,因为安装程序检测到修改并且它拒绝继续。我真的很喜欢自动部署,之前的覆盖效果很好。

最佳答案

您可以做的一件事是在您的代码中添加一个首次运行的部分,以执行其他设置,例如修改应用程序配置文件。要检测是否需要完成此设置,您的第三方配置部分可能会预先填充您的应用程序将识别为属于新安装的虚拟值。例如,您的配置文件可能如下所示:

<thirdPartySection>
<add key="someKey" value="#NEEDS_INITIALIZED#" />
</thirdPartySection >

您的 Main 方法可能如下所示:

static public void Main(params string[] args)
{
const string uninitializedValue = "#NEEDS_INITIALIZED#";

// Load the third-party config section (this assumes it inherits from
// ConfigurationElementCollection
var config = ConfigurationManager.OpenExeConfiguration(
ConfigurationUserLevel.None);
var section = config.GetSection("thirdPartySection")
as NameValueConfigurationCollection;
var setting = section["someKey"];
if (setting.Value == uninitializedValue)
{
setting.Value = PolicyTrackerInfo.OverwriteString;
config.Save();
}
}

关于.net - 在运行时或安装时修改 App.config 中的配置部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2113814/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com