首页 > 解决方案 > 从同一解决方案 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项目类读取ConnectionStringapp.config文件:

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

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

WinForms项目UserInterface中,我有一个按钮,可以像WebService一样启动Common项目中的例程。

但是,如果我将UserInterface项目“设置为启动项目”,则前面的代码会引发错误,因为我没有在UserInterface项目中指定。ConfigurationManager.AppSettings["ConnectionString"]ConnectionStringapp.config

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

标签: c#.netwcfapp-config

解决方案


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


推荐阅读