在运行时或安装时修改App.config中的配置节

时间:2010-01-21 23:29:54

标签: .net app-config namevaluecollection

我有一个使用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环境安装在。

目前我在运行时进行了一些其他配置更改,但这些更改位于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"); 部分,因此很容易获得。我在搜索解决方案时发现了许多引用,但它们似乎依赖于具有自定义类的部分,而不是我所面临的NameValueCollection。

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

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

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;

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

{{1}}

到目前为止,这么好。但是,我没有看到允许我用修改后的数据替换旧XML的方法。 是否可以在运行时使用?

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

3 个答案:

答案 0 :(得分:1)

为了提出一个人们可以投票或投票的想法(不是除了围绕这个问题的风滚草之外我已经看过很多),我正在考虑使用这里发布的技术:http://www.devx.com/dotnet/Article/10045 < / p>

基本思想是让ClickOnce部署一个shim应用程序,它只会对主应用程序进行XCOPY部署(因为它不使用app.config文件,我可以使用标准的XML修改技术并完成它)。

或者,当从网络部署此应用程序时,我可能只是将程序集放在网络上并使用权限系统授予其访问所需的文件夹和数据库的权限。有什么想法吗?

答案 1 :(得分:1)

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

<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();
    }
}

答案 2 :(得分:0)

我会编写一个custom installer,并在AfterInstall事件中使用上面的XML机制修改配置文件。但是,我不知道如何或如果它适用于ClickOnce。

相关问题