【问题标题】:Is it possible to load web-config from console application?是否可以从控制台应用程序加载 web-config?
【发布时间】:2012-11-12 17:01:39
【问题描述】:

我的问题很简单。我有一个第三方库,它假定它将在网站中使用(需要 web.config 中的特殊配置部分)。我想在 C# 控制台应用程序中使用这个库。有可能的?

我试过了 WebConfigurationManager.OpenWebConfiguration(); 以及将所有内容复制到 app.config 中,但它不起作用。我收到的错误是 ConfigurationErrorsException 说明 An error occurred creating the configuration section handler for ...: Could not load type 'Configuration.RenderingSection' from assembly 'System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.

【问题讨论】:

    标签: c# web-applications configuration console-application


    【解决方案1】:

    您可以通过AppDomain.CurrentDomain.SetData(string name, Object data) 设置APP_CONFIG_FILE

    string webconfigPath = "whatever......../web.config");
    string webconfigDir = Path.GetDirectoryName(configPath);
    
    AppDomain.CurrentDomain.SetData("APPBASE", webconfigDir);
    AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", webconfigPath);
    

    这很简单,您将获得控制台应用程序 (cron) 和 Web 应用程序的相同设置。

    【讨论】:

    • 简单明了。我是否可以建议您更改您提供的示例以使用 web.config 的实际伪路径而不是“whatever......./web.config”。只是为了清楚
    • @Loligans 我不知道实际路径。我想这取决于您项目的相对位置。
    【解决方案2】:

    请改用app.config

    语法、选项等与 web.config 完全相同,但适用于控制台和 WinForms 应用程序。

    另外,看看here,虽然我还没有测试过,但它似乎对这个人有用。但是,如果您的项目与 web 无关,我仍然建议使用 app.config。

    【讨论】:

    • 拥有大量相同设置的 .config 文件并不是一个好主意。当控制台应用程序与网站一起部署时,将所有设置集中在一个文件中是明智的。只需考虑一个依赖控制台应用程序来启动定期批处理的 Web 系统。
    • @YvánEcarri 你知道如何像你说的那样在应用程序之间共享配置文件吗?这是我的确切设置,但我无法让它工作......
    猜你喜欢
    • 2011-01-26
    • 1970-01-01
    • 1970-01-01
    • 2011-04-22
    • 2016-10-29
    • 2018-06-19
    • 1970-01-01
    • 2015-04-02
    • 2021-10-30
    相关资源
    最近更新 更多