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

时间:2019-04-16 09:19:15

标签: c# .net wcf

我有一个名为 WebServiceProject 的解决方案。

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

  • 通用 (类库)
  • 用户界面 (WinForms项目)
  • Web服务 (WCF服务项目)

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 项目中的例程作为 WebService 启动。 strong>确实。

但是如果我将 UserInterface 项目“ 设置为启动项目”,则上一段代码ConfigurationManager.AppSettings["ConnectionString"]会引发错误,因为我没有指定{strong> UserInterface 项目中的ConnectionString中的app.config

所以,我的问题是:如果我设置为启动项目,我如何从 WebService 项目事件中读取ConnectionString属性> UserInterface 项目?更笼统地说,如何从另一个与执行的项目不同的项目中读取app.config属性?

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

我发现此链接非常有用:

AppSettings in App or Web Config Using a Linked File

感谢@ Daniel Stackendland

答案 2 :(得分:-1)

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

相关问题