I need to know how to count the no of keys in app settings and manipulate through them in class file...
For example I'll have my app config as follows
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="Mysqlrateteller" value="server=localhost;Database=rateteller;User Id=root;Password=;"/>
<add key="Mysqlrateteller1" value="server=localhost;Database=rateteller1;User Id=root;Password=;"/>
<add key="Mysqlrateteller2" value="server=localhost;Database=rate;User Id=root;Password=;"/>
</appSettings>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>
Here i may have n no of keys. And i need to count the no of keys available in a class file of this project. how to do it?
You can do like this:
var appSettings = System.Configuration.ConfigurationManager.AppSettings;
int cntAppSettingKeys = appSettings.Count;
AppSettings is a NameValueCollection. So below code will work
System.Configuration.ConfigurationManager.AppSettings.Count
Related
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
I have a app.config looking like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<appSettings>
<add key="Setting1" value="value1" />
<add key="Setting2" value="value2" />
</appSettings>
</configuration>
Is it possible to somehow read the whole section of settings? Instead of just calling them one by one:
private static readonly string Setting1 = ConfigurationManager.AppSettings["Setting1"];
private static readonly int Setting2 = ConfigurationManager.AppSettings["Setting2"];
Is that possible? If not by this way, how should I achieve this (was thinking about creating an own Settings.xml but I wanna try this first).
Just directly use the object returned by ConfigurationManager.AppSettings: it has a whole load of other members.
eg.
var as = ConfigurationManager.AppSettings;
foreach (string k in as.AllKeys) {
Console.WriteLine("{0}: {1}", k, as[k]);
}
Here below is App.Config Code
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<appSettings>
<add key="DBServer" value="Localhost"/>
<add key="DBServer" value="Sql2005rs"/>
<add key="DBName" value="Everest"/>
</appSettings>
</configuration>
I Am trying to get the values Local Host and Sql2005rs to return in a combo box this is what I'm using can anyone tell me why it is failing.
public Form1()
{
InitializeComponent();
var DBServerNames = ConfigurationManager.AppSettings.AllKeys .Where(key => key.StartsWith("DBServer")) .Select (key => ConfigurationManager.AppSettings[key]) .ToArray();
DBServer.Items.AddRange(DBServerNames);
}
Yet it only return sql2005rs anyone know why?
You will always get the last one when you have multiple settings with the same key. When you have multiple of the same key each one gets overridden by the next.
So rather than do that, which really isn't a very good thing to do - the key is supposed to be unique, as in any key/value dictionary - change your settings to something like :
<appSettings>
<add key="DBServers" value="Localhost,Sql2005rs"/>
<add key="DBName" value="Everest"/>
</appSettings>
Then just pluck out the DBServers value and parse that. Something like:
string[] myServers= ConfigurationManager.AppSettings["DBServers"].Split(',');
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 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.