簡體   English   中英

從 .NET 中的 app.config 或 web.config 讀取設置

[英]Reading settings from app.config or web.config in .NET

我正在處理C# class庫,該庫需要能夠從DLL申請中讀取web.configapp.config文件中的設置。

我發現了

ConfigurationSettings.AppSettings.Get("MySetting")

有效,但該代碼已被 Microsoft 標記為已棄用。

我讀過我應該使用:

ConfigurationManager.AppSettings["MySetting"]

但是, System.Configuration.ConfigurationManager class 似乎無法從 C# Class 庫項目中獲得。

做這個的最好方式是什么?

對於如下所示的示例 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;

如果還沒有,您可能還需要在項目中添加對System.Configuration的引用。 然后,您可以像這樣訪問值:

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

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

你絕對應該使用ConfigurationManager在過時的ConfigurationSettings

.NET Framework 4.5 和 4.6 的更新; 以下將不再起作用:

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

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

string keyvalue = Properties.Settings.Default.keyname;

有關更多信息,請參閱管理應用程序設置

右鍵單擊您的類庫,然后從菜單中選擇“添加引用”選項。

然后從 .NET 選項卡中,選擇 System.Configuration。 這會將 System.Configuration DLL 文件包含到您的項目中。

我正在使用它,它對我來說效果很好:

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

從配置中讀取:

您需要添加對配置的引用:

  1. 在您的項目中打開“屬性”
  2. 轉到“設置”選項卡
  3. 添加“名稱”和“值”
  4. 使用以下代碼獲取價值:

     string value = Properties.Settings.Default.keyname;

保存到配置:

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

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

您可能要將 App.config 文件添加到 DLL 文件中。 App.Config 僅適用於可執行項目,因為所有 DLL 文件都從正在執行的 EXE 文件的配置文件中獲取配置。

假設您的解決方案中有兩個項目:

  • 某個DLL
  • 某個執行器

您的問題可能與您將 app.config 文件包含到 SomeDLL 而不是 SomeExe 的事實有關。 SomeDll 能夠從 SomeExe 項目中讀取配置。

嘗試這個:

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

web.config文件中,這應該是下一個結構:

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

我有同樣的問題。 只需這樣閱讀: System.Configuration.ConfigurationSettings.AppSettings["MySetting"]

步驟 1:右鍵單擊引用選項卡以添加引用。

第 2 步:單擊程序集選項卡

第 3 步:搜索“System.Configuration”

第四步:點擊確定。

然后它會起作用。

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

因為我發現通過在 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
}

web.config與 Web 應用程序一起使用。 web.config默認有幾個 web 應用程序所需的配置。 您可以為 Web 應用程序下的每個文件夾創建一個web.config

app.config用於 Windows 應用程序。 在 Visual Studio 中構建應用程序時,它會自動重命名為<appname>.exe.config並且此文件必須與應用程序一起交付。

您可以使用相同的方法從兩個配置文件中調用app settings值:System.Configuration.ConfigurationSettings.AppSettings["Key"]

我強烈建議您為此調用創建一個包裝器 類似於ConfigurationReaderService並使用依賴注入來獲取此類。 通過這種方式,您將能夠隔離此配置文件以進行測試。

所以使用ConfigurationManager.AppSettings["something"]; 建議並返回此值。 如果 .config 文件中沒有任何可用的密鑰,則使用此方法您可以創建某種默認返回值。

此外,您可以使用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>();

為了完整起見,還有一個僅適用於 Web 項目的選項:System.Web.Configuration.WebConfigurationManager.AppSettings["MySetting"]

這樣做的好處是不需要添加額外的引用,因此對於某些人來說可能更可取。

我總是創建一個 IConfig 接口,其中包含為所有配置值聲明的類型安全屬性。 Config 實現類然后包裝對 System.Configuration 的調用。 您所有的 System.Configuration 調用現在都集中在一個地方,維護和跟蹤正在使用的字段並聲明它們的默認值變得更加容易和干凈。 我編寫了一組私有輔助方法來讀取和解析常見數據類型。

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

ConfigurationManager 不是您訪問自己的設置所需要的。

為此,您應該使用

{YourAppName}.Properties.Settings.{settingName}

我能夠使以下方法適用於 .NET Core 項目:

腳步:

  1. 在您的項目中創建一個 appsettings.json(格式如下)。
  2. 接下來創建一個配置類。 格式如下。
  3. 我創建了一個 Login() 方法來顯示配置類的用法。

    在您的項目中使用內容創建 appsettings.json:

     { "Environments": { "QA": { "Url": "somevalue", "Username": "someuser", "Password": "somepwd" }, "BrowserConfig": { "Browser": "Chrome", "Headless": "true" }, "EnvironmentSelected": { "Environment": "QA" } } public static class Configuration { private static IConfiguration _configuration; static Configuration() { var builder = new ConfigurationBuilder() .AddJsonFile($"appsettings.json"); _configuration = builder.Build(); } public static Browser GetBrowser() { if (_configuration.GetSection("BrowserConfig:Browser").Value == "Firefox") { return Browser.Firefox; } if (_configuration.GetSection("BrowserConfig:Browser").Value == "Edge") { return Browser.Edge; } if (_configuration.GetSection("BrowserConfig:Browser").Value == "IE") { return Browser.InternetExplorer; } return Browser.Chrome; } public static bool IsHeadless() { return _configuration.GetSection("BrowserConfig:Headless").Value == "true"; } public static string GetEnvironment() { return _configuration.GetSection("EnvironmentSelected")["Environment"]; } public static IConfigurationSection EnvironmentInfo() { var env = GetEnvironment(); return _configuration.GetSection($@"Environments:{env}"); } } public void Login() { var environment = Configuration.EnvironmentInfo(); Email.SendKeys(environment["username"]); Password.SendKeys(environment["password"]); WaitForElementToBeClickableAndClick(_driver, SignIn); }

如果您需要/想要使用ConfigurationManager類...

您可能需要通過NuGet 包管理器加載System.Configuration.ConfigurationManager

工具->NuGet 包管理器->管理解決方案的 NuGet 包...

微軟文檔

文檔中值得注意的一件事......

如果您的應用程序需要對其自己的配置進行只讀訪問,我們建議您使用 GetSection(String) 方法。 此方法提供對當前應用程序緩存的配置值的訪問,它比 Configuration 類具有更好的性能。

幾天來,我一直試圖找到解決同一問題的方法。 我能夠通過在web.config文件的 appsettings 標記中添加一個鍵來解決這個問題。 使用幫助程序時,這應該覆蓋 .dll 文件。

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

另一種可能的解決方案:

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

您可以使用以下行。 在我的情況下,它正在工作: System.Configuration.ConfigurationSettings.AppSettings["yourKeyName"]

您必須注意上面的代碼行也是舊版本,並且在新庫中已棄用。

請檢查您正在使用的 .NET 版本。 它應該高於 4。並且您必須將 System.Configuration 系統庫添加到您的應用程序中。

額外:如果您正在處理類庫項目,則必須嵌入settings.json文件。

類庫不應該直接引用 app.config 中的任何內容——該類沒有 app.config,因為它不是應用程序,而是一個類。

  1. 轉到 JSON 文件的屬性。
  2. 更改構建操作 -> 嵌入式資源。
  3. 使用下面的代碼來閱讀它。

var assembly = Assembly.GetExecutingAssembly();

var resourceStream = assembly.GetManifestResourceStream("Assembly.file.json");

string myString = reader.ReadToEnd();

現在我們有了一個 JSON 字符串,我們可以使用JsonConvert反序列化它

如果您沒有將文件嵌入到程序集中,則不能只使用 DLL 文件而不使用該文件

我正在使用 Visual Studio for Mac 版本 17.0.6。

正如您在此屏幕截圖中看到的,無法添加對 System.Configuration 的引用

在此處輸入圖像描述

解決方案:

  1. 安裝 NuGet Package - System.Configuration.ConfigurationManager。
  2. 創建 app.config 文件並將“構建操作”設置為“EmbeddedResource”
<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <appSettings>
        <add key="name" value="Joe"/>
    </appSettings>
</configuration>
  1. 使用 System.Configuration;
  2. 請享用)

字符串名稱 = ConfigurationManager.AppSettings["name"];

我在這個鏈接https://stackoverflow.com/a/1836938/1492229中找到了答案

不僅需要使用命名空間System.Configuration 您還必須添加對程序集System.Configuration.dll的引用,通過

  1. 右鍵單擊引用/依賴
  2. 選擇添加參考
  3. 查找並添加System.Configuration

這肯定會起作用。 同樣對於NameValueCollection你必須寫:

using System.Collections.Specialized;

這是一個例子: App.config

<applicationSettings>
    <MyApp.My.MySettings>
        <setting name="Printer" serializeAs="String">
            <value>1234 </value>
        </setting>
    </MyApp.My.MySettings>
</applicationSettings>

Dim strPrinterName as string = My.settings.Printer

暫無
暫無

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

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