根据配置模式的不同,应用程序设置不同

Different application settings depending on configuration mode

提问人:Maxim Gershkovich 提问时间:6/22/2010 更新时间:7/9/2021 访问量:32962

问:

有没有人知道我可以在 .Net 应用程序中设置应用程序(或用户)级别设置的方法,这些设置以应用程序当前开发模式为条件?IE:调试/发布

更具体地说,我在应用程序设置中保存了一个对我的 Web 服务的 url 引用。在发布模式下,我希望这些设置指向 http://myWebservice.MyURL.com 在调试模式下,我希望这些设置 http://myDebuggableWebService.MyURL.com

有什么想法吗?

C# .NET vb.net 设置 AppSettings

评论


答:

7赞 hhravn 6/22/2010 #1

据我所知,没有内置的方法可以做到这一点。在我们的项目中,我们维护了 4 个不同的设置文件,并通过在构建的预构建步骤中将每个文件复制到活动文件中来在它们之间切换。

copy "$(ProjectDir)properties\settings.settings.$(ConfigurationName).xml" "$(ProjectDir)properties\settings.settings"
copy "$(ProjectDir)properties\settings.designer.$(ConfigurationName).cs" "$(ProjectDir)properties\settings.Designer.cs"

几年来,这对我们来说非常有效。只需更改目标,整个配置文件也会切换。

编辑:这些文件被命名为例如、l 等。settings.settings.Debug.xmlsettings.settings.Release.xm

斯科特·汉塞尔曼(Scott Hanselman)描述了一种稍微“聪明”的方法,唯一的区别是我们没有检查文件是否已更改:http://www.hanselman.com/blog/ManagingMultipleConfigurationFileEnvironmentsWithPreBuildEvents.aspx

4赞 jadusty 6/22/2010 #2

如果要将所有内容保存在一个配置文件中,可以在 app.settings 中引入自定义配置部分,以存储调试和发布模式的属性。

您可以将对象保留在应用中,以存储特定于开发人员模式的设置,也可以基于调试开关覆盖现有应用设置。

下面是一个简短的控制台应用示例 (DevModeDependencyTest):

App.config :

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <sectionGroup name="DevModeSettings">
      <section name="debug" type="DevModeDependencyTest.DevModeSetting,DevModeDependencyTest" allowLocation="true" allowDefinition="Everywhere" />
      <section name="release" type="DevModeDependencyTest.DevModeSetting,DevModeDependencyTest" allowLocation="true" allowDefinition="Everywhere" />
    </sectionGroup>
  </configSections>
  <DevModeSettings>
    <debug webServiceUrl="http://myDebuggableWebService.MyURL.com" />
    <release webServiceUrl="http://myWebservice.MyURL.com" />
  </DevModeSettings>
  <appSettings>
    <add key="webServiceUrl" value="http://myWebservice.MyURL.com" />
  </appSettings>
</configuration>

用于存储自定义配置的对象 (DevModeSettings.cs):

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

namespace DevModeDependencyTest
{
    public class DevModeSetting : ConfigurationSection
    {
        public override bool IsReadOnly()
        {
            return false;
        }

        [ConfigurationProperty("webServiceUrl", IsRequired = false)]
        public string WebServiceUrl
        {
            get
            {
                return (string)this["webServiceUrl"];
            }
            set
            {
                this["webServiceUrl"] = value;
            }
        }
    }
}

用于访问自定义配置设置 (DevModeSettingsHandler.cs) 的处理程序:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

namespace DevModeDependencyTest
{
    public class DevModeSettingsHandler
    {
        public static DevModeSetting GetDevModeSetting()
        {
            return GetDevModeSetting("debug");
        }

        public static DevModeSetting GetDevModeSetting(string devMode)
        {
            string section = "DevModeSettings/" + devMode;

            ConfigurationManager.RefreshSection(section); // This must be done to flush out previous overrides
            DevModeSetting config = (DevModeSetting)ConfigurationManager.GetSection(section);

            if (config != null)
            {
                // Perform validation etc...
            }
            else
            {
                throw new ConfigurationErrorsException("oops!");
            }

            return config;
        }
    }
}

最后,控制台应用的入口点 (DevModeDependencyTest.cs) :

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

namespace DevModeDependencyTest
{
    class DevModeDependencyTest
    {
        static void Main(string[] args)
        {
            DevModeSetting devMode = new DevModeSetting();

            #if (DEBUG)
                devMode = DevModeSettingsHandler.GetDevModeSetting("debug");
                ConfigurationManager.AppSettings["webServiceUrl"] = devMode.WebServiceUrl;
            #endif

            Console.WriteLine(ConfigurationManager.AppSettings["webServiceUrl"]);
            Console.ReadLine();
        }
    }
}
15赞 dotNET 9/19/2012 #3

我知道这是几年前被问到的,但以防万一有人正在寻找我使用的简单有效的解决方案。

  1. 转到项目属性的“设置”选项卡(你将看到 Web 服务 URL 或此处已列出的任何其他设置)。

  2. 单击“设置”页面上的“查看代码”按钮。

  3. 在构造函数中键入 this。

    this.SettingsLoaded += Settings_SettingsLoaded;
    
  4. 在构造函数下添加以下函数:

    void Settings_SettingsLoaded(object sender, System.Configuration.SettingsLoadedEventArgs e)
    {
        #if(DEBUG)
        this["YOUR_SETTING_NAME"] = VALUE_FOR_DEBUG_CONFIGURATION;
        #else
        this["YOUR_SETTING_NAME"] = VALUE_FOR_RELEASE_CONFIGURATION;
        #endif
    }
    

现在,每当您运行项目时,它只会编译与当前生成配置匹配的行。

评论

0赞 Steve Smith 4/17/2018
您在哪里/如何指定每个配置的更改?例如,如果我创建一个名为“QARelease”的配置,我将如何检查这是当前的配置?
0赞 dotNET 4/17/2018
不确定我是否正确理解了您,但是有用于区分 DEBUG 和 RELEASE 配置的预处理器指令。此外,您可以为每个配置定义自己的编译符号,并在 中使用它们。#if(DEBUG)#if
0赞 Steve Smith 4/17/2018
谢谢。我不确定你是从哪里来的。DEBUG
3赞 Konrad Brodzik 1/28/2013 #4

SlowCheetah 不仅为 App.config 添加了您要求的功能,还为项目中的任何 XML 文件添加了您要求的功能 - http://visualstudiogallery.msdn.microsoft.com/69023d00-a4f9-4a34-a6cd-7e854ba318b5

评论

1赞 Spontifixus 1/28/2013
虽然这在理论上可以回答这个问题,但最好在这里包括答案的基本部分,并提供链接以供参考。
0赞 David Faivre 12/6/2013
我认为这可能是最好的答案——它似乎允许每个构建配置 app.config 转换(很像 web.config 转换中的构建)。
18赞 ne1410s 12/18/2014 #5

这对聚会来说有点晚了,但我偶然发现了一种实现文件方法的好方法。(即它利用命名空间web.transformapp.confighttp://schemas.microsoft.com/XML-Document-Transform)

我认为它“很好”,因为它是一种纯 xml 方法,不需要第三方软件。

  • 父/默认 App.config 文件是根据各种生成配置派生的。
  • 然后,这些后代只会覆盖它们需要的内容。

在我看来,这比必须维护 x 个配置文件要复杂和强大得多,这些配置文件被完整复制,例如在其他答案中。

此处发布了演练:http://mitasoft.wordpress.com/2011/09/28/multipleappconfig/


看,妈妈 - 我的 IDE 中没有明确的构建后事件!

评论

0赞 Patrick 4/4/2018
工作,谢谢!如果您使用的是 VS 2017,并且出现找不到 Web*.targets 的错误,请查看此答案 stackoverflow.com/a/45354395/2964949
1赞 Jean-François Beauchamp 8/31/2018
对于 VS 2017,必须替换为 in 。v10.0v15.0<Import Project="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v15.0\Web\Microsoft.Web.Publishing.targets" />
2赞 Papa Mufflon 10/31/2018
用于任何 Visual Studio 版本(从链接中的注释)。Project=”$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Web\Microsoft.Web.Publishing.targets”
1赞 StackOverthrow 12/8/2018
现在有一个 VS 插件:配置转换
0赞 IronHide 2/8/2023
这在 .net core 中有效吗?它对我不起作用,看起来从未使用过调试和发布文件
1赞 TGasdf 2/10/2016 #6

我有一个类似的问题需要解决,最终使用了 XDT (web.config) 转换引擎,这在 ne1410s 的答案中已经建议过,可以在这里找到: https://stackoverflow.com/a/27546685/410906

但是我没有按照他的链接中的描述手动执行,而是使用了这个插件: https://visualstudiogallery.msdn.microsoft.com/579d3a78-3bdd-497c-bc21-aa6e6abbc859

该插件仅帮助设置配置,不需要构建,并且可以在其他计算机或构建服务器上构建解决方案,而无需插件或任何其他工具。