从同一解决方案 C# 中的另一个项目读取配置属性

Read config properties from another project in the same solution C#

我有一个名为 WebServiceProject.

的解决方案

在此解决方案中,我有三个项目:

WebService 项目中,我有一个包含以下内容的 app.config 文件:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b72a5b561321d079">
      <section name="WebService.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b72a5b561321d079" requirePermission="false"/>
    </sectionGroup>
  </configSections>
  <startup>
  <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/></startup>
  <appSettings>
    <add key="ConnectionString" value="mydatabase@localhost"/>
  </appSettings>
  <system.serviceModel>
    <bindings/>
    <client/>
  </system.serviceModel>
</configuration>

WebService 项目中,我执行了一些预定例程调用 Common 项目 类 读取 ConnectionString来自 app.config 个文件:

if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["ConnectionString"]))
{
    // I do something
}

如果我单独启动 WebService 一切正常。

WinForms 项目 UserInterface 中,我有一个按钮可以在 Common[=61] 中启动例程=] 项目与 WebService 一样。

但是如果我“设置为启动项目UserInterface 项目前一段代码 ConfigurationManager.AppSettings["ConnectionString"] 抛出错误,因为我没有在 UserInterface 项目中的 app.config 中指定 ConnectionString

所以,我的问题是:如果我“Set作为 StartUp 项目" UserInterface 项目?更一般地说,我如何从不同于已执行项目的另一个项目中读取 app.config 属性?

您可以将 Web 服务项目中的应用程序设置放入 UI 项目的 app.config 中。

只需读取文件并将其解析为 XML。然后检索你value阅读感兴趣的key

我发现这个 link 非常有用:

AppSettings in App or Web Config Using a Linked File

感谢@Daniel Stackendland