简体   繁体   English

从 .NET 中的 app.config 或 web.config 读取设置

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

I'm working on a C# class library that needs to be able to read settings from the web.config or app.config file (depending on whether the DLL is referenced from an ASP.NET web application or a Windows Forms application).我正在处理C# class库,该库需要能够从DLL申请中读取web.configapp.config文件中的设置。

I've found that我发现了

ConfigurationSettings.AppSettings.Get("MySetting")

works, but that code has been marked as deprecated by Microsoft.有效,但该代码已被 Microsoft 标记为已弃用。

I've read that I should be using:我读过我应该使用:

ConfigurationManager.AppSettings["MySetting"]

However, the System.Configuration.ConfigurationManager class doesn't seem to be available from a C# Class Library project.但是, System.Configuration.ConfigurationManager class 似乎无法从 C# Class 库项目中获得。

What is the best way to do this?做这个的最好方式是什么?

For a sample app.config file like below:对于如下所示的示例 app.config 文件:

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

You read the above application settings using the code shown below:您可以使用下面显示的代码阅读上述应用程序设置:

using System.Configuration;

You may also need to also add a reference to System.Configuration in your project if there isn't one already.如果还没有,您可能还需要在项目中添加对System.Configuration的引用。 You can then access the values like so:然后,您可以像这样访问值:

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

You'll need to add a reference to System.Configuration in your project's references folder .您需要在项目的引用文件夹中添加System.Configuration引用

You should definitely be using the ConfigurationManager over the obsolete ConfigurationSettings .你绝对应该使用ConfigurationManager在过时的ConfigurationSettings

Update for .NET Framework 4.5 and 4.6; .NET Framework 4.5 和 4.6 的更新; the following will no longer work:以下将不再起作用:

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

Now access the Setting class via Properties:现在通过属性访问设置类:

string keyvalue = Properties.Settings.Default.keyname;

See Managing Application Settings for more information.有关更多信息,请参阅管理应用程序设置

Right click on your class library, and choose the "Add References" option from the Menu.右键单击您的类库,然后从菜单中选择“添加引用”选项。

And from the .NET tab, select System.Configuration.然后从 .NET 选项卡中,选择 System.Configuration。 This would include the System.Configuration DLL file into your project.这会将 System.Configuration DLL 文件包含到您的项目中。

我正在使用它,它对我来说效果很好:

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

Read From Config:从配置中读取:

You'll need to add a reference to the configuration:您需要添加对配置的引用:

  1. Open "Properties" on your project在您的项目中打开“属性”
  2. Go to "Settings" Tab转到“设置”选项卡
  3. Add "Name" and "Value"添加“名称”和“值”
  4. Get Value with using following code:使用以下代码获取价值:

     string value = Properties.Settings.Default.keyname;

Save to the configuration:保存到配置:

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

您必须向项目添加对 System.Configuration 程序集的引用。

You might be adding the App.config file to a DLL file.您可能要将 App.config 文件添加到 DLL 文件中。 App.Config works only for executable projects, since all the DLL files take the configuration from the configuration file for the EXE file being executed. App.Config 仅适用于可执行项目,因为所有 DLL 文件都从正在执行的 EXE 文件的配置文件中获取配置。

Let's say you have two projects in your solution:假设您的解决方案中有两个项目:

  • SomeDll某个DLL
  • SomeExe某个执行器

Your problem might be related to the fact that you're including the app.config file to SomeDLL and not SomeExe.您的问题可能与您将 app.config 文件包含到 SomeDLL 而不是 SomeExe 的事实有关。 SomeDll is able to read the configuration from the SomeExe project. SomeDll 能够从 SomeExe 项目中读取配置。

Try this:尝试这个:

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

In the web.config file this should be the next structure:web.config文件中,这应该是下一个结构:

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

I had the same problem.我有同样的问题。 Just read them this way: System.Configuration.ConfigurationSettings.AppSettings["MySetting"]只需这样阅读: System.Configuration.ConfigurationSettings.AppSettings["MySetting"]

Step 1: Right-click on references tab to add reference.步骤 1:右键单击引用选项卡以添加引用。

Step 2: Click on Assemblies tab第 2 步:单击程序集选项卡

Step 3: Search for 'System.Configuration'第 3 步:搜索“System.Configuration”

Step 4: Click OK.第四步:点击确定。

Then it will work.然后它会起作用。

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

As I found the best approach to access application settings variables in a systematic way by making a wrapper class over System.Configuration as below因为我发现通过在 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);
        }
    }
}

Now we can access needed settings variables by hard coded names using another class as below:现在我们可以使用另一个类通过硬编码名称访问所需的设置变量,如下所示:

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 is used with web applications. web.config与 Web 应用程序一起使用。 web.config by default has several configurations required for the web application. web.config默认有几个 web 应用程序所需的配置。 You can have a web.config for each folder under your web application.您可以为 Web 应用程序下的每个文件夹创建一个web.config

app.config is used for Windows applications. app.config用于 Windows 应用程序。 When you build the application in Visual Studio, it will be automatically renamed to <appname>.exe.config and this file has to be delivered along with your application.在 Visual Studio 中构建应用程序时,它会自动重命名为<appname>.exe.config并且此文件必须与应用程序一起交付。

You can use the same method to call the app settings values from both configuration files: System.Configuration.ConfigurationSettings.AppSettings["Key"]您可以使用相同的方法从两个配置文件中调用app settings值:System.Configuration.ConfigurationSettings.AppSettings["Key"]

I strongly recommend you to create a wrapper for this call.我强烈建议您为此调用创建一个包装器 Something like a ConfigurationReaderService and use dependency injection to get this class.类似于ConfigurationReaderService并使用依赖注入来获取此类。 This way you will be able to isolate this configuration files for test purposes.通过这种方式,您将能够隔离此配置文件以进行测试。

So use the ConfigurationManager.AppSettings["something"];所以使用ConfigurationManager.AppSettings["something"]; suggested and return this value.建议并返回此值。 With this method you can create some kind of default return if there isn't any key available in the .config file.如果 .config 文件中没有任何可用的密钥,则使用此方法您可以创建某种默认返回值。

Also, you can use Formo :此外,您可以使用Formo

Configuration:配置:

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

Code:代码:

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>();

Just for completeness, there's another option available for web projects only: System.Web.Configuration.WebConfigurationManager.AppSettings["MySetting"]为了完整起见,还有一个仅适用于 Web 项目的选项:System.Web.Configuration.WebConfigurationManager.AppSettings["MySetting"]

The benefit of this is that it doesn't require an extra reference to be added, so it may be preferable for some people.这样做的好处是不需要添加额外的引用,因此对于某些人来说可能更可取。

I always create an IConfig interface with typesafe properties declared for all configuration values.我总是创建一个 IConfig 接口,其中包含为所有配置值声明的类型安全属性。 A Config implementation class then wraps the calls to System.Configuration. Config 实现类然后包装对 System.Configuration 的调用。 All your System.Configuration calls are now in one place, and it is so much easier and cleaner to maintain and track which fields are being used and declare their default values.您所有的 System.Configuration 调用现在都集中在一个地方,维护和跟踪正在使用的字段并声明它们的默认值变得更加容易和干净。 I write a set of private helper methods to read and parse common data types.我编写了一组私有辅助方法来读取和解析常见数据类型。

Using an IoC framework you can access the IConfig fields anywhere your in application by simply passing the interface to a class constructor.使用IoC框架,您可以通过简单地将接口传递给类构造函数来访问应用程序中任何位置的 IConfig 字段。 You're also then able to create mock implementations of the IConfig interface in your unit tests so you can now test various configuration values and value combinations without needing to touch your App.config or Web.config file.然后,您还可以在单​​元测试中创建 IConfig 接口的模拟实现,以便您现在可以测试各种配置值和值组合,而无需接触 App.config 或 Web.config 文件。

The ConfigurationManager is not what you need to access your own settings. ConfigurationManager 不是您访问自己的设置所需要的。

To do this you should use为此,您应该使用

{YourAppName}.Properties.Settings.{settingName}

I was able to get the below approach working for .NET Core projects:我能够使以下方法适用于 .NET Core 项目:

Steps:脚步:

  1. Create an appsettings.json (format given below) in your project.在您的项目中创建一个 appsettings.json(格式如下)。
  2. Next create a configuration class.接下来创建一个配置类。 The format is provided below.格式如下。
  3. I have created a Login() method to show the usage of the Configuration Class.我创建了一个 Login() 方法来显示配置类的用法。

    Create appsettings.json in your project with content:在您的项目中使用内容创建 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); }

If your needing/wanting to use the ConfigurationManager class...如果您需要/想要使用ConfigurationManager类...

You may need to load System.Configuration.ConfigurationManager by Microsoft via NuGet Package Manager您可能需要通过NuGet 包管理器加载System.Configuration.ConfigurationManager

Tools->NuGet Package Manager->Manage NuGet Packages for Solution...工具->NuGet 包管理器->管理解决方案的 NuGet 包...

Microsoft Docs 微软文档

One thing worth noting from the docs...文档中值得注意的一件事......

If your application needs read-only access to its own configuration, we recommend that you use the GetSection(String) method.如果您的应用程序需要对其自己的配置进行只读访问,我们建议您使用 GetSection(String) 方法。 This method provides access to the cached configuration values for the current application, which has better performance than the Configuration class.此方法提供对当前应用程序缓存的配置值的访问,它比 Configuration 类具有更好的性能。

I have been trying to find a fix for this same issue for a couple of days now.几天来,我一直试图找到解决同一问题的方法。 I was able to resolve this by adding a key within the appsettings tag in the web.config file.我能够通过在web.config文件的 appsettings 标记中添加一个键来解决这个问题。 This should override the .dll file when using the helper.使用帮助程序时,这应该覆盖 .dll 文件。

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

Another possible solution:另一种可能的解决方案:

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

You can use the below line.您可以使用以下行。 In my case it was working: System.Configuration.ConfigurationSettings.AppSettings["yourKeyName"]在我的情况下,它正在工作: System.Configuration.ConfigurationSettings.AppSettings["yourKeyName"]

You must take care that the above line of code is also the old version and it's deprecated in new libraries.您必须注意上面的代码行也是旧版本,并且在新库中已弃用。

Please check the .NET version you are working on.请检查您正在使用的 .NET 版本。 It should be higher than 4. And you have to add the System.Configuration system library to your application.它应该高于 4。并且您必须将 System.Configuration 系统库添加到您的应用程序中。

extra : if you are working on a Class Library project you have to embed the settings.json file.额外:如果您正在处理类库项目,则必须嵌入settings.json文件。

A class library shouldn't really be directly referencing anything in app.config - the class doesn't have an app.config, because it's not an application, it's a class.类库不应该直接引用 app.config 中的任何内容——该类没有 app.config,因为它不是应用程序,而是一个类。

  1. Go to the JSON file's properties.转到 JSON 文件的属性。
  2. Change Build Action -> Embedded resource.更改构建操作 -> 嵌入式资源。
  3. Use the following code to read it.使用下面的代码来阅读它。

var assembly = Assembly.GetExecutingAssembly();

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

string myString = reader.ReadToEnd();

now we have a JSON string we can Deserialize it using JsonConvert现在我们有了一个 JSON 字符串,我们可以使用JsonConvert反序列化它

if you didn't embed the file inside the assembly you can't use only the DLL file without the file如果您没有将文件嵌入到程序集中,则不能只使用 DLL 文件而不使用该文件

I'm using Visual Studio for Mac version 17.0.6.我正在使用 Visual Studio for Mac 版本 17.0.6。

As you can see on this screenshot it is not possible to add a reference to System.Configuration .正如您在此屏幕截图中看到的,无法添加对 System.Configuration 的引用

在此处输入图像描述

Solution:解决方案:

  1. install NuGet Package - System.Configuration.ConfigurationManager.安装 NuGet Package - System.Configuration.ConfigurationManager。
  2. Create app.config file and set "Build action" to "EmbeddedResource"创建 app.config 文件并将“构建操作”设置为“EmbeddedResource”
<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <appSettings>
        <add key="name" value="Joe"/>
    </appSettings>
</configuration>
  1. using System.Configuration;使用 System.Configuration;
  2. enjoy)请享用)

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

I found the answer in this link https://stackoverflow.com/a/1836938/1492229我在这个链接https://stackoverflow.com/a/1836938/1492229中找到了答案

It's not only necessary to use the namespace System.Configuration .不仅需要使用命名空间System.Configuration You have also to add the reference to the assembly System.Configuration.dll , by您还必须添加对程序集System.Configuration.dll的引用,通过

  1. Right-click on the References / Dependencies右键单击引用/依赖
  2. Choose Add Reference选择添加参考
  3. Find and add System.Configuration .查找并添加System.Configuration

This will work for sure.这肯定会起作用。 Also for the NameValueCollection you have to write:同样对于NameValueCollection你必须写:

using System.Collections.Specialized;

Here's an example: App.config这是一个例子: 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