I encountered a problem that I have no way to parse a document standard configurations.
For example:
private string GetConfigKey(string param)
{
Configuration dllConfig = ConfigurationManager.OpenExeConfiguration(this.GetType().Assembly.Location);
AppSettingsSection dllConfigAppSettings = (AppSettingsSection)dllConfig.GetSection("appSettings");
return dllConfigAppSettings.Settings[param].Value;
}
As a result, I get the settings from the file in a form:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="host" value="mail.ololo.by"/>
</appSettings>
<configSections>
<section name="provideConfig" type="System.Configuration.DictionarySectionHandler"/>
<section name="provideMailStatus" type="System.Configuration.DictionarySectionHandler" />
</configSections>
<provideConfig>
<add key="post#gate.ololo.by" value="Mail Subject 1"/>
<add key="guga#gate.ololo.by" value="Mail Subject 2"/>
</provideConfig>
<provideMailStatus>
<add key="status1" value="send"/>
<add key="status2" value="draft"/>
<add key="status2" value="other"/>
</provideMailStatus>
</configuration>
but
Hashtable hashtable =
(Hashtable)ConfigurationManager.GetSection("provideConfig");
foreach (DictionaryEntry dictionaryEntry in hashtable)
{
Console.WriteLine(dictionaryEntry.Key+" "+dictionaryEntry.Value);
}
but that's unfortunately a configSections have a problem. I can not seem to get it.
MB, I go in the wrong direction?
P.S. Config file cannot be named "app.config" - only project dll name
Config file should be named as executable file name and ".config". Even this executable file uses this dll-file.
For example: ConSoleApplication.exe uses MyLibrary.dll. Then config file must be named ConSoleApplication.exe.config
If You need some other name for config file read this
Thank you all, I coped with the problem.
I can tell if someone will be interested.
Configuration Section Designer Codeplex
.NET Configuration Code Generator
Best regards, yauhen.
Related
I need a second .config to manage alot of keys. I tried using
<configSections>
<section name="apiConnection" type="CustomConfig.apiConnectionSection, CustomConfig" />
</configSections>
<apiConnection configSource ="ApiConnection.config"/>
Where "ApiConnection.config" is my .config file to manage keys but this didn't work.
Then i tried the "file" property in appSettings.
<appSettings file="ApiConnection.config">
This didn't work either. I Tried with:
../ApiConnection.config
~/ApiConnection.config
But nothing...
Some ideas?
The program doesnt break, just not show me the keys when i try with the ConfigurationManager.
https://i.stack.imgur.com/6xHK2.png
<img src= https://i.stack.imgur.com/6xHK2.png/>
EDIT
My file is in root path (with web.config)
The file looks like
<?xml version="1.0" encoding="utf-8"?>
<appSettings>
<add key="Secret" value="z8xyHkN3Eju2TS9u-4MXeI2AbZiuTsF7xYJcjIJ" />
<add key="Audience" value="keyforms"/>
</appSettings>
Ok I think I know what your problem is based on your last comment.
This code is creating a new configuration section called apiConnection.
<configSections>
<section name="apiConnection" type="CustomConfig.apiConnectionSection, CustomConfig" />
</configSections>
<apiConnection configSource ="ApiConnection.config"/>
This section's values will not be contained in app settings. So you won't be able to access it via
ConfigurationManager.AppSettings
You will need to access it in a different manner. Now the exact manner will depend on your implementation of CustomConfig.apiConnectionSection and CustomConfig. I would search your code to find the class that defines how this works.
This example shows how to pull values from a custom config section, SecureAppSettings that uses the NameValueCollection in the same manner as AppSettings. You will have to do some digging to figure out what Types you will need to utilize.
NameValueCollection section = (NameValueCollection)ConfigurationManager.GetSection("secureAppSettings");
string userName = section["userName"];
I need to read web.config file, outside the application's folder (located in any other directory).
I tried this code:
string filePath = #"C:\Users\Idrees\Downloads\New folder\Web.config";
Configuration c1 = ConfigurationManager.OpenExeConfiguration(filePath);
var value1 = c1.AppSettings.Settings["Key1"].Value;
But it is giving me the error:
Object reference not set to an instance of an object.
Because here, c1.AppSettings is an object, but c1.AppSettings.Settings contains not items (hence 0 Count). It is not really loading the AppSettings keys. When trying to read any Key from Settings collection, it gives this error.
Is there any way how to load AppSettings keys from a web.config file outside the application folder.
If I put same file within application folder, then it reads the keys successfully.
This is my sample config file's content:
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<connectionStrings>
<!--here goes my connection strings-->
</connectionStrings>
<appSettings>
<add key="Key1" value="Value1" />
<add key="Key2" value="Value2" />
<add key="Key3" value="Value3" />
</appSettings>
</configuration>
I have a web application already running on my server. And I need to develop a small utility which has to do some job in database, and I don't want to write db credentials or connection string(and some other additional app-settings) in each application, I want it to read same thing from web.config.
You can using ConfigurationManager to read arbitrary configuration files by opening a mapped exe configuration as follows:
var filePath = #"C:\Users\Idrees\Downloads\New folder\Web.config";
var fileMap = new ExeConfigurationFileMap { ExeConfigFilename = filePath };
var configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
var value = configuration.AppSettings.Settings["Key1"].Value;
As I understand from your comment you want some kind of shared configuration accross multiple app on the same computer. You may consider using external file like this :
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<connectionStrings configSource="config\connString01.config"/>
<appSettings file="config\config01.config">
<add key="Var3" value="Var3 value from main config file"/>
</appSettings>
in above .config example connectionStrings is sourced from an other file. Below an example what can be such an external config file:
<connectionStrings>
<add name="SQLConnectionString01" connectionString="Data Source=sourcename01;Initial Catalog=cat01;Persist Security Info=True;Integrated Security=true;"/>
</connectionStrings>
Read documentation: ConfigurationManager.OpenExeConfiguration on MSDN
public static Configuration OpenExeConfiguration(
string exePath
)
This is EXE path
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>
I am writing a program in visual studio,now i can't get the value of app.config.My app.config look like this:
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="connStr" connectionString="Data Source=Dolphin-PC;Initial Catalog=jsptpd_SYS;Persist Security Info=True;User ID=sa;Password=ccir"/>
</connectionStrings>
</configuration>
And the code i am try to get the value:
try
{
con2 = System.Configuration.ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
logger.Info("try to get connectionstr success:" + connStr);
}
catch(Exception ex)
{
logger.Info("try to get connectionstr failed:" + ex.ToString());
}
The log's output:
2013-12-14 16:22:28,710 [1] INFO ApplicationInfoLog [(null)] <(null)>
- try to get connectionstr failed:System.NullReferenceException:
object reference not set to instance.
on Jsptpd.JobScheduler.jsptpdJobScheduler..ctor()
location D:\jsptpd\Code\jsptpdJobScheduler\jsptpdJobScheduler\jsptpdJobShedule.cs:line 46
Where is wrong? Why can't read the ConnectionStrings?
Your section is declared as NameValueSectionHandler. As this article points out, this handler returns a NameValueCollection, not the IDictionary that you cast it to afterwards. That's why as IDictionary results in a null value.
Either declare your section as DictionarySectionHandler or change IDictionary to NameValueCollection.
If that config you posted is really what you have, then that config is just plain wrong.... you have two nested <configuration> sections - that won't ever work!
If your config really looks like what you posted, you need to change it to look like this:
<?xml version="1.0"?>
<configuration> <!-- one and ONLY one <configuration> node! -->
<configSections> <!-- directly under <configuration> -->
<section name="quartz" type="System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0,Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
<configSections>
<connectionStrings> <!-- directly under <configuration> -->
<add name="connStr" connectionString="Data Source=Dolphin-PC;Initial Catalog=jsptpd_SYS;Persist Security Info=True;User ID=sa;Password=ccir"/>
</connectionStrings>
<quartz> <!-- directly under <configuration> -->
...........
</quartz>
<appSettings> <!-- directly under <configuration> -->
<add key="connStr" value="Data Source=Dolphin-PC;Initial Catalog=jsptpd_SYS;Persist Security Info=True;User ID=sa;Password=ccir"/>
</appSettings>
</configuration>
There should be only one <configuration> section, and all other tags, like <configSections>, <quartz>, <connectionStrings> and <appSettings> should be directly inside the one and only <configuration> element
Check your app.config file attribute set,make sure that Generate Operation is not embeded resource.
Because you read the app.config through ConfiguationManager class,the Configuration read file like this:
http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.aspx
•Read and write configuration files as a whole. Your application can read and write configuration settings at any level, for itself or for other applications or computers, locally or remotely. Use one of the methods provided by the ConfigurationManager class to open a configuration file such as SampleApp.exe.config. These methods return a Configuration object that in turn exposes methods and properties you can use to work with the associated configuration files. The methods perform read or write operations and create the configuration data every time that a file is written.
If you set embeded resource,the bin directionary could not generate the SampleApp.exe.config file,so the ConfigurationManager could read your config file.
So if you want to correct the problem,do this
choose the app.config file in resource manager of visual studio:
set the copy to outout dirctionary to:
No copy
set the generte operation to:
None
The problem will fixed.
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();