How to read app.config file programmatically - c#

I have config file for my app, my app.config is as below
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="System.Configuration.IgnoreSectionHandler" />
</configSections>
<appSettings>
<add key="log4net.Config" value="log4netConfig.xml" />
<add key="proxyaddress" value="192.168.130.5"/>
</appSettings>
<system.net>
<defaultProxy enabled ="true" useDefaultCredentials = "true">
<proxy autoDetect="false"
bypassonlocal="true"
proxyaddress="192.168.130.6"
scriptLocation="https://ws.mycompany.com/proxy.dat"
usesystemdefault="true"
/>
</defaultProxy>
</system.net>
</configuration>
var proxy= ConfigurationManager.AppSettings["proxyaddress"];
will get "192.168.130.5",
How to get all proxy settings in system.net section in c#?
Updated: I changed my config to the following and get it:
string proxyURLAddr = ConfigurationManager.AppSettings["proxyaddress"];
Config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="System.Configuration.IgnoreSectionHandler" />
</configSections>
<appSettings>
<add key="log4net.Config" value="log4netConfig.xml" />
<add key="proxyaddress" value=""/>
</appSettings>
<system.net>
<defaultProxy enabled ="true" useDefaultCredentials = "true">
<proxy usesystemdefault ="True" bypassonlocal="False"/>
</defaultProxy>
</system.net>
</configuration>

toosensitive, your app.config when built and deployed will be renamed to : name of of your assembly + (.exe or .dll) + ".config". The answer above is valid for web applications, but not for console ones, libraries and windows services. You can't put app.config alongside with any assembly and expect this assembly to start reading the appSettings section, the same way IIS reads web.config files. I think this is why you receive null.

Update 2:
You can read the values like described here but for local app settings configuration file:
var proxy = System.Configuration.ConfigurationManager.GetSection("system.net/defaultProxy") as System.Net.Configuration.DefaultProxySection
if (proxy != null)
{ /* Check Values Here */ }
For custom sections you can use the following steps:
You have define a custom configsection class derived from ConfigurationSection:
public class ProxyConfiguration : ConfigurationSection
{
private static readonly ProxyConfiguration Config = ConfigurationManager.GetSection("proxy") as ProxyConfiguration;
public static ProxyConfiguration Instance
{
get
{
return Config;
}
}
[ConfigurationProperty("autoDetect", IsRequired = true, DefaultValue = true)]
public bool AutoDetect
{
get { return (bool)this["autoDetect"]; }
}
// all other properties
}
After that you can use the class instance to access the values:
ProxyConfiguration.Instance.AutoDetect
You can find an example in MSDN

Related

Custom section in App.Config, ConfigurationManager stops working

I have created a console app in c# that reads information from App.config. if i add things in appSettings section, i can acces them and it works, but as soon as i add some custom sections i cant read anything from it. I am using ConfigurationManager, and i have the reference for it included.
My app config looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<appSettings>
<add key="overwriteBackupFiles" value="False"/>
<add key="path" value="c:\temp"/>
</appSettings>
<ImageFormatsINeed>
<add key="type1" value="width=180&height=180"></add>
<add key="type2" value="width=220&height=220"></add>
<add key="type3" value="width=500&height=500"></add>
</ImageFormatsINeed>
</configuration>
and i am trying to acces those information like this:
string path = ConfigurationManager.AppSettings["path"];
var settings = ConfigurationManager.GetSection("ImageFormatsINeed");
When i didnt have the ImageFormatsINeed section i could get the path from AppSettings and it was working. But as soon as i added my ImageFormatsINeed section, everything stops working.
Now my question is how can i add custom sections in app.config that it will work, or should i just read my ImageInformation from some custom xml file or config file?
You have to use the tag <configSections> at the top in your app.config, for this case you should use the type AppSettingsSection
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="ImageFormatsINeed" type="System.Configuration.AppSettingsSection" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<appSettings>
<add key="overwriteBackupFiles" value="False"/>
<add key="path" value="c:\temp"/>
</appSettings>
<ImageFormatsINeed>
<add key="type1" value="width=180&height=180"></add>
<add key="type2" value="width=220&height=220"></add>
<add key="type3" value="width=500&height=500"></add>
</ImageFormatsINeed>
</configuration>
Then in your C# code:
NameValueCollection settings_section = ConfigurationManager.GetSection("ImageFormatsINeed") as NameValueCollection;
Console.WriteLine(settings_section["type1"]);

How to use custom configuration file or app.config in .NET application

I have MVC5 .NET 4.6.1 C# web application
I want to create a custom config file separate from web.config to store some settings my application uses.
I tried to follow this article https://support.microsoft.com/en-us/kb/815786
however the items I set in app.config:
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.6.1" />
<httpRuntime targetFramework="4.6.1" />
</system.web>
<appSettings>
<add key="Key0" value="0" />
<add key="Key1" value="1" />
<add key="Key2" value="2" />
</appSettings>
</configuration>
are not seen in my application see , eg. they come as null:
string attr = ConfigurationManager.AppSettings["Key0"];
Why isn't it working? Am I missing something?
Alternatively I would like to create a custom config file eg. mycustom.config to define my global app settings.
EDIT
Solution I used
Follwing this post https://social.msdn.microsoft.com/Forums/vstudio/en-US/11e6d326-c32c-46b1-a9a2-1fbef96f33ee/howto-custom-configuration-files?forum=netfxbcl
In web.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="newAppSettings" type="System.Configuration.AppSettingsSection, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</configSections>
<newAppSettings file="C:\mycustom.config"/>
</configuration>
Then mycustom.config
<?xml version="1.0" encoding="utf-8" ?>
<newAppSettings>
<add key="OurKey" value="OurValue"/>
</newAppSettings>
And reading the value:
System.Collections.Specialized.NameValueCollection newAppSettings = (System.Collections.Specialized.NameValueCollection)System.Configuration.ConfigurationManager.GetSection("newAppSettings");
string key = Convert.ToDateTime(newAppSettings["OurKey"]);
You can use separate config file for connection strings and app settings:
<appSettings configSource="appSettings.config" />
<connectionStrings configSource="connectionStrings.config"/>
appSettings.config file
<?xml version="1.0" encoding="utf-8" ?>
<appSettings>
<add key="Setting1" value="App setting 1" />
</appSettings>
connectionStrings.config file
<?xml version="1.0" encoding="utf-8"?>
<connectionStrings>
<add name="MyConnStr1" connectionString="My connection string" />
</connectionStrings>
Usage is same as it was before:
var setting1 = ConfigurationManager.AppSettings["Setting1"];
var connString1 = ConfigurationManager.ConnectionStrings["MyConnStr1"].ConnectionString;
//Helps to open the Root level web.config file.
Configuration webConfigApp = WebConfigurationManager.OpenWebConfiguration("~");
//Modifying the AppKey from AppValue to AppValue1
webConfigApp.AppSettings.Settings["AppKey"].Value = "AppValue1";
<appSettings>
<add key="AppKey" value="AppValue"/>
</appSettings>

How to programmatically read the custom config files in asp.net mvc

In the root folder of my ASP.NET MVC 5 I have two config files. one is the default web.config file and the second one is department.config.
The content of the department.config file is:
<department>
<add key="dept1" value="xyz.uvw.rst" />
<add key="dept2" value="abc.def.ghi" />
<department>
How to read the department.config file ?
I want to get a collection of values under <department> in this config file.
Edit: Web.config has <department configSource="reports.config" />
so, how to read the configSource file in asp.net mvc ?
Edit:
<configuration>
<configSections>
<section name="departments"
type="System.Configuration.AppSettingsSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
restartOnExternalChanges="false"
requirePermission="false" />
In your web.config, you can specify other files that the built-in ConfigurationManager can easily access. For example, we decided that we wanted to separate connection strings and application setting into separate files. You can do this by putting this in your web.config:
<appSettings configSource="appsettings.config" />
Then you can access these values in the 'regular' way
ConfigurationManager.AppSettings["KeyHere"]
Same thing with connection strings...
Why not use the appSettings section in your web.config? These are easy to read using ConfigurationManager object.
In your web.config, find the appSettings section:
<appSettings>
<add key="dept1" value="xyz.uvw.rst"/>
Then in your class where you want to read it, import the correct namespace:
using System.Configuration;
And then read the value easily, like so:
var dept1 = ConfigurationManager.AppSettings.Get("dept1");
If you have to have it in a separate config, you might consider creating a class for it, I'll post up an example of that shortly.
edit1: here is a quick example of how to do your own custom config
first, define the config class:
using System;
using System.Configuration;
namespace WebApplication2
{
public class MyConfig : ConfigurationSection
{
private static readonly MyConfig ConfigSection = ConfigurationManager.GetSection("MyConfig") as MyConfig;
public static MyConfig Settings
{
get
{
return ConfigSection;
}
}
[ConfigurationProperty("Dept1", IsRequired = true)]
public string Dept1
{
get
{
return (string)this["Dept1"];
}
set
{
this["Dept1"] = value;
}
}
[ConfigurationProperty("Dept2", IsRequired = true, DefaultValue = "abc.def.ghi")]
public string Dept2
{
get
{
return (string)this["Dept2"];
}
set
{
this["Dept2"] = value;
}
}
// added as example of different types
[ConfigurationProperty("CheckDate", IsRequired = false, DefaultValue = "7/3/2014 1:00:00 PM")]
public DateTime CheckDate
{
get
{
return (DateTime)this["CheckDate"];
}
set
{
this["CheckDate"] = value;
}
}
}
}
Then, set it up in your web.config file:
<configuration>
<configSections>
<section name="MyConfig" type="WebApplication2.MyConfig, WebApplication2" />
</configSections>
<MyConfig Dept1="xyz.uvw.rst" Dept2="abc.def.ghi" />
...
</configuration>
And then you can call it very easily, along with strong-typing and support for many types:
var dept1 = MyConfig.Settings.Dept1;
var dept2 = MyConfig.Settings.Dept2;
// strongly-typed
DateTime chkDate = MyConfig.Settings.CheckDate;
That's how I would do it. Use the built-in stuff and create a class for it. Easy to do config transforms with, easy to read, and easy to use.
This is an old question but in the event someone needs to know... First geekzsters answer lays out how to write a config class. Then you specify a custom Config Section and give it a configSource in a separate file.
<configuration>
<configSections>
<section name="myCustomSection" type="MyNamespace.MyCustomType" requirePermission="false" />
</configSections>
</configuration>
<myCustomSection configSource="myConfigDir\myFile.config" />
Then in your custom config file you write a normal xml config
<?xml version="1.0" encoding="utf-8"?>
<myCustomSection>
<myCustomType>
<add name="pro1" value="abc" />
<add name="prop2" value="cde" />
<add name="prop3" value="efg" />
</myCustomType>
</myCustomSection>
The simplest way to read configuration File other then Web config is to define file you want to read as follows:
webConfig
<appSettings file="TestFile.config">
<add key="webpages:Version" value="3.0.0.0"/>
<add key="webpages:Enabled" value="false"/>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
TestFile.Config
<appSettings>
<add key="test" value="testData"/>
</appSettings>
Above we define the file we want to read configuration from in Webconfig. thus using ConfigurationManager.AppSettings['test'] you can read the value from your newly created custom config file.

Error : The key 'SecurityKey' does not exist in the appSettings configuration section

When I execute my app (Winform)from the computer where it was developed there is no error, but When I execute this in another computer I get the error. My App.config is like this:
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="SecurityKey"/>
</appSettings>
<startup>
<supportedRuntime version="v4.0"sku="...."/>
</startup>
</configuration>
and this is the line that I use:
string key = (string)settingsReader.GetValue("SecurityKey", typeof(String));
I already tried to follow this The key 'UserID' does not exist in the appSettings configuration section, but it is still the same.
Any suggestions?
the appSettings in the .config file is different from .settings file.
Take a look at ConfigurationManager.AppSettings Property.
I'd also mention that I have no idea how either the settingsReader nor the ConfigurationManager work with a key with no value:
<add key="SecurityKey"/> <!-- no value? -->
<add key="SecurityKeyWithValue" value="myvalue"/>
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="SecurityKey" value="Syed Moshiur Murshed"/>
</appSettings>
</configuration>

How to use ConfigurationManager.AppSettings with a custom section?

I need to get "http://example.com" from using App.config file.
But at the moment I am using:
string peopleXMLPath = ConfigurationManager.AppSettings["server"];
I cannot get the value.
Could you point out what I am doing wrong?
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<configSections>
<section name="device" type="System.Configuration.SingleTagSectionHandler" />
<section name="server" type="System.Configuration.SingleTagSectionHandler" />
</configSections>
<device id="1" description="petras room" location="" mall="" />
<server url="http://example.com" />
</configuration>
I think you need to get the config section, and access that:
var section = ConfigurationManager.GetSection("server") as NameValueCollection;
var value = section["url"];
And you also need to update your config file:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<configSections>
<section name="device" type="System.Configuration.NameValueSectionHandler" />
<section name="server" type="System.Configuration.NameValueSectionHandler" />
</configSections>
<device>
<add key="id" value="1" />
<add key="description" value="petras room" />
<add key="location" value="" />
<add key="mall" value="" />
</device>
<server>
<add key="url" value="http://example.com" />
</server>
</configuration>
Edit: As CodeCaster mentioned in his answer, SingleTagSectionHandler is for internal use only. I think NameValueSectionHandler is the preferred way to define config sections.
The SingleTagSectionHandler documentation says:
This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.
You can retrieve it as a HashTable and access its entries using Configuration.GetSection():
Hashtable serverTag = (Hashtable)ConfigurationManager.GetSection("server");
string serverUrl = (string)serverTag["url"];
string peopleXMLPath = ConfigurationManager.AppSettings["server"];
gets the value from the appSettings part of the app.config file but you are storing your value in
<server url="http://example.com" />
Either put the value in the appSettings section as below or retrieve the value from its current location.
You need to add a key value pair to your config's appSettings section. As below:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="server" value="http://example.com" />
</appSettings>
</configuration>
Your reading code is correct but you should probably check for null. If the code fails to read the config value the string variable will be null.
You're defining a configuration section instead of a value in AppSettings. You can simply add your setting to AppSettings:
<appSettings>
... may be some settings here already
<add key="server" value="http://example.com" />
</appSettings>
Custom config sections are typically used for more complicated configurations (e.g. multiple values per key, non-string values, etc.
If you want to get the value from the app settings your appsetting element in configuration file must have a key.
define your sever value as mentioned below under configuration section:
<configuration>
<appSettings>
<add key="server" value="http://example.com" />
</appSettings>
...
...
...
</configuration>
Now execute below code line to get the server url:
string peopleXMLPath = ConfigurationManager.AppSettings["server"].ToString();

Categories

Resources