Reading settings from app.config or web.config in .NET

只愿长相守 提交于 2019-12-16 22:23:07

问题


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).

I've found that

ConfigurationSettings.AppSettings.Get("MySetting")

works, but that code has been marked as deprecated by 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.

What is the best way to do this?


回答1:


You'll need to add a reference to System.Configuration in your project's references folder.

You should definitely be using the ConfigurationManager over the obsolete ConfigurationSettings.




回答2:


For Sample App.config like below:

<?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 app settings using 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. You can then access the values like so:

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

Hope this helps!




回答3:


Update for framework 4.5 and 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.




回答4:


Right click on your class Library, and choose the "Add References" option from the Menu; and finally from the .NET tab, select System.Configuration. This would include System.Configuration dll into your project.




回答5:


I'm using this, and it works well for me:

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



回答6:


Read From Config :

You'll need to add a reference to Config

  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 Config :

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



回答7:


You must add to the project a reference to the System.Configuration assembly.




回答8:


You might be adding the App.config file to a DLL. App.Config works only for executable projects, since all the dll take the configuration from the configuration file for the exe being executed.

Let's say you have two projects in your solution:

  • SomeDll
  • SomeExe

Your problem might be releated to the fact that you're including the app.config to SomeDLL and not SomeExe. SomeDll is able to read the configuration from the SomeExe project.




回答9:


Try this:

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

In web.config should be next structure:

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



回答10:


I had the same problem, just read them this way:

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



回答11:


web.config is used with web applications.web.config by default has several configurations required for the web application. You can have a web.config for each folder under your web application.

app.config is used for windows applications. When you build the application in vs.net, it will be automatically renamed to <appname>.exe.config and this file has to be delivered along with your application.

You can use the same method to call the app settings values from both config files :

System.Configuration.ConfigurationSettings.AppSettings["Key"]



回答12:


As i found best approach to access app settings variables in systematic way by making a wrapper class over System.Configuration as below

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
    }



回答13:


I strongly recommend you to create a Wrapper for this call. Something like a ConfigurationReaderService and use dependency injection to get this class. This way you will be able to isolate this configuration files for test purposes.

So use the ConfigurationManager.AppSettings["something"]; suggested and return this value. You can with this method create some kind of default return if there is no key available in .config file.




回答14:


Also, you can use formo:

Config:

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



回答15:


Just for completeness, there's another option available for web projects only:

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

The benefit of this is that it doesn't require an extra reference to be added so may be preferable for some people.




回答16:


I always create an IConfig interface with typesafe properties declared for all configuration values. A Config implementation class then wrappers the calls to System.Configuration. All your System.Configuration calls are now in one place so much easier and cleaner to maintain and track which fields are being used and declare their default values. 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 app by simply passing the interface to a class constructor. 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.




回答17:


Step 1: Right-click on references tab to add reference.

Step 2: Click on Assemblies tab

Step 3: Search for 'System.Configuration'

Step 4: Click OK.

Then It will work

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



回答18:


I have been trying to find a fix for this same issue for a couple days now. I was able to resolve this by adding a key within the appsettings tag in the web.config. This should override the .dll when using the helper.

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



回答19:


Another possible solution:

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



回答20:


you can use below line, in my case it was working:

System.Configuration.ConfigurationSettings.AppSettings["yourKeyName"]

you must take care that above line of code is also old version and its deprecated in new libraries.




回答21:


The ConfigurationManager is not what you need to access your own settings

To do this you should use the

{YourAppName}.Properties.Settings.{settingName}




回答22:


Pls check .net version you are working. It should be higher than 4. And you have to add System.Configuration system library to your application




回答23:


I was able to get below approach working for .netcore projects:

Steps :

i) Create an appsettings.json ( format given below ) in your project ii) Next create a configuration class, the format provided below. iii) I have created a Login() method to show the usage of the Configuration Class.

Create appsettings.json in your project with content :
`
{
  "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);
        }
`



回答24:


here's an example: 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


来源:https://stackoverflow.com/questions/1189364/reading-settings-from-app-config-or-web-config-in-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!