2009-07-27 153 views
569

我正在研究C#類庫,它需要能夠從web.configapp.config文件中讀取設置(具體取決於DLL是否從ASP引用.NET Web應用程序或Windows窗體應用程序)。從.net中的app.config或web.config讀取設置

我發現

ConfigurationSettings.AppSettings.Get("MySetting") 

作品,但這些代碼已經被打上了微軟爲廢棄。

我讀過,我應該使用:

ConfigurationManager.AppSettings["MySetting"] 

然而,System.Configuration.ConfigurationManager類似乎並沒有提供從C#類庫項目。

有誰知道這樣做的最好方法是什麼?

+22

就像我讀4倍MSDN的例子和文章。而在這裏降落了。只需添加一個參考文獻..他們爲什麼不能這麼說呢。好問題! +1 – ppumkin 2012-09-14 10:18:56

+0

如果你想**寫回設置**,請看** [這裏](https://stackoverflow.com/a/11841175/1016343)**你如何做到這一點。 – Matt 2017-07-17 11:16:40

+0

[AppSettings vs applicationSettings(.NET app.config/Web.config)]的優缺點](https://stackoverflow.com/questions/460935/pros-and-cons-of-appsettings-vs-applicationsettings配置網絡配置) – Matt 2017-07-17 11:17:36

回答

613

你需要添加引用System.Configuration在項目的引用文件夾

您應該一直在使用ConfigurationManager而不是過時的ConfigurationSettings

18

您必須在項目中添加對System.Configuration程序集的引用。

34

右鍵單擊您的類庫,然後從菜單中選擇「添加引用」選項;最後從.NET選項卡中選擇System.Configuration。這將包括System.Configuration DLL到您的項目中。使用

+0

添加引用後,能夠做 `ConfigurationManager.ConnectionStrings [0] .ConnectionString` – SushiGuy 2017-12-20 20:41:10

27

林這一點,它很適合我

textBox1.Text = ConfigurationManager.AppSettings["Name"]; 
+39

TS明確指出,他使用相同的代碼,但他的項目無法編譯(由於缺少參考,因爲它結果)。 -1不讀這個問題。 – Isantipov 2013-03-12 17:28:57

1

web.config被使用的Web應用程序。 web.config默認會有幾個Web應用程序所需的配置。您可以爲您的Web應用程序下的每個文件夾使用web.config

app.config用於Windows應用程序。當您在vs.net中構建應用程序時,它將自動更名爲<appname>.exe.config,並且此文件必須隨應用程序一起交付。

您可以用同樣的方法從兩個配置文件調用app settings值:

System.Configuration.COnfigurationSettings.AppSettings["Key"] 
+0

也可以使用```System.Configuration.COnfigurationSettings.AppSettings.Get(「Key」)```而不是使用方括號。 – Mason 2017-12-19 09:24:02

625

對於樣品的App.config象下面這樣:

<?xml version="1.0" encoding="utf-8" ?> 
<configuration> 
    <appSettings> 
    <add key="countoffiles" value="7" /> 
    <add key="logfilelocation" value="abc.txt" /> 
    </appSettings> 
</configuration> 

您閱讀使用代碼上面的應用程序設置如下所示:

using System.Configuration; 

您可能還需要添加對Sys的引用如果您的項目中沒有人,請在您的項目中進行配置。你可以這樣訪問值:

string configvalue1 = ConfigurationManager.AppSettings["countoffiles"]; 
string configvalue2 = ConfigurationManager.AppSettings["logfilelocation"]; 

希望這有助於!

+83

我比你接受的答案更喜歡你的答案。例子的答案總是爲我做的伎倆。 – 2014-02-04 07:36:27

+2

爲什麼upvotes?這根本不回答這個問題。 – Gigo 2014-06-16 14:03:03

+14

@Gigo這將顯示* how *如何使用Configuration Manager,包括一個App。配置示例以及示例代碼。接受的答案不是。 – crashmstr 2014-07-29 14:11:00

2

我強烈建議你爲這個調用創建一個Wrapper。就像ConfigurationReaderService,並使用依賴注入來獲得這個類。這樣你就可以隔離這個配置文件用於測試目的。所以使用ConfigurationManager.AppSettings["something"];建議並返回這個值。如果在.config文件中沒有可用的密鑰,則可以使用此方法創建某種默認返回。

0

我一直在試圖找到一個解決這個問題幾天。我能夠通過在web.config中的appsettings標籤內添加一個鍵來解決此問題。這應該在使用助手時覆蓋.dll。

<configuration> 
<appSettings> 
<add key="loginUrl" value="~/RedirectValue.cshtml" /> 
<add key="autoFormsAuthentication" value="false"/> 
</appSettings> 
</configuration> 
12

您可能正在將App.config文件添加到DLL中。 App.Config僅適用於可執行項目,因爲所有的dll都從正在執行的exe文件的配置文件中進行配置。

比方說,你有你的解決方案兩個項目:

  • SomeDll
  • SomeExe

你的問題可能是相關型號給你,包括在app.config到SomeDLL事實而不是SomeExe。 SomeDll能夠從SomeExe項目讀取配置。

5

我有同樣的問題,只是讀他們這樣說:

System.Configuration.ConfigurationSettings.AppSettings["MySetting"] 
5

試試這個:

string keyvalue=System.Configuration.ConfigurationManager.AppSettings["keyname"]; 

在web.config中應該是一個結構:

<configuration> 
<appSettings> 
<add key="keyname" value="keyvalue" /> 
</appSettings> 
</configuration> 
1

而且,您可以使用formo

配置:

<appSettings> 
    <add key="RetryAttempts" value="5" /> 
    <add key="ApplicationBuildDate" value="11/4/1999 6:23 AM" /> 
</appSettings> 

代碼:

dynamic config = new Configuration(); 
var retryAttempts1 = config.RetryAttempts;     // returns 5 as a string 
var retryAttempts2 = config.RetryAttempts(10);    // returns 5 if found in config, else 10 
var retryAttempts3 = config.RetryAttempts(userInput, 10); // returns 5 if it exists in config, else userInput if not null, else 10 
var appBuildDate = config.ApplicationBuildDate<DateTime>(); 
46

更新框架4.5和4.6;以下將不再工作:

string keyvalue=System.Configuration.ConfigurationManager.AppSettings["keyname"]; 

通過屬性現在訪問設置類:

string keyvalue= Properties.Settings.Default.keyname; 

更多信息請參見Managing Application Settings

0

我總是創建一個帶有爲所有配置值聲明的類型安全屬性的IConfig接口。一個Config實現類然後包裝對System.Configuration的調用。所有的System.Configuration調用現在都在一個地方,更容易和更清晰地維護和跟蹤哪些字段正在使用並聲明它們的默認值。我編寫了一套私有的幫助器方法來讀取和解析常見的數據類型。

使用IoC框架,只需將接口傳遞給類構造函數,即可訪問應用程序中任何位置的IConfig字段。您還可以在單​​元測試中創建IConfig接口的模擬實現,以便您現在可以測試各種配置值和值組合,而無需觸摸App.config或Web.config文件。

0

只是爲了保持完整性,有僅適用於Web項目的另一種選擇:

System.Web.Configuration.WebConfigurationManager.AppSettings["MySetting"] 

這樣做的好處是,它不需要額外的參考如此添加可能是優選的一些人。

0

另一種可能的解決方案:

var MyReader = new System.Configuration.AppSettingsReader(); 
string keyvalue = MyReader.GetValue("keyalue",typeof(string)).ToString(); 
6

閱讀從配置:

你需要參考您的項目添加到配置

  1. 打開 「屬性」
  2. 圍棋到「設置」標籤
  3. 添加「名稱」和「值」
  4. 使用以下代碼獲取值:

    string value = Properties.Settings.Default.keyname;

保存到配置:

Properties.Settings.Default.keyName = value; 
    Properties.Settings.Default.Save(); 
1

因爲我發現通過使在System.Configuration的包裝類,如下

public class BaseConfiguration 
    { 
     protected static object GetAppSetting(Type expectedType, string key) 
     { 
      string value = ConfigurationManager.AppSettings.Get(key); 
      try 
      { 
       if (expectedType == typeof(int)) 
        return int.Parse(value); 
       if (expectedType == typeof(string)) 
        return value; 

       throw new Exception("Type not supported."); 
      } 
      catch (Exception ex) 
      { 
       throw new Exception(string.Format("Config key:{0} was expected to be of type {1} but was not.", 
        key, expectedType), ex); 
      } 
     } 
    } 

我們訪問系統的方式應用程序設置變量,最好的辦法我們可以通過使用另一個類的硬編碼名稱訪問所需的設置變量,如下所示

public class ConfigurationSettings:BaseConfiguration 
    { 
     #region App setting 

     public static string ApplicationName 
     { 
      get { return (string)GetAppSetting(typeof(string), "ApplicationName"); } 
     } 

     public static string MailBccAddress 
     { 
      get { return (string)GetAppSetting(typeof(string), "MailBccAddress"); } 
     } 

     public static string DefaultConnection 
     { 
      get { return (string)GetAppSetting(typeof(string), "DefaultConnection"); } 
     } 

     #endregion App setting 

     #region global setting 



     #endregion global setting 
    } 
-3

爲前:

<applicationSettings> 
     <MyApp.My.MySettings> 
      <setting name="Printer" serializeAs="String"> 
       <value>1234 </value> 
      </setting> 
     </MyApp.My.MySettings> 
    </applicationSettings> 
Dim strPrinterName as string= My.settings.Printer 
相關問題