簡體   English   中英

從同一解決方案C#中的另一個項目中讀取配置屬性

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

我有一個名為WebServiceProject的解決方案。

在這個解決方案中我有三個項目:

  • 共同 (類庫)
  • UserInterface (WinForms項目)
  • WebService (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項目中,我執行一些調度例程,調用從app.config文件讀取ConnectionStringCommon項目類:

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

如果我單獨啟動WebService一切正常。

WinForms項目UserInterface中 ,我有一個按鈕,可以像WebService那樣在Common項目中啟動例程。

但是如果我“ 設置為StartUp項目 ”,則UserInterface項目的前一段代碼ConfigurationManager.AppSettings["ConnectionString"]拋出錯誤,因為我沒有在UserInterface項目的app.config中指定ConnectionString

所以,我的問題是:如果我將“ 設置為StartUp項目 ”作為UserInterface項目,如何從WebService項目事件中讀取ConnectionString屬性? 更一般地說,如何從另一個與執行項目不同的項目中讀取app.config屬性?

只需讀取文件並將其解析為XML 然后檢索讀取感興趣key value

我發現這個鏈接非常有用:

使用鏈接文件在App或Web配置中進行AppSettings

感謝@ Daniel Stackendland

您可以將Web服務項目中的應用程序設置放入UI項目的app.config中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM