.net and .config files - c#

I have the following stored in a stores.config file inside my asp.net website's root folder.
<configuration>
<appSettings>
<add key="ClientId" value="127605460617602"/>
<add key ="RedirectUrl" value="http://localhost:49548/Redirect.aspx"/>
</appSettings>
</configuration>
How can I use string Clientid = ConfigurationManager.AppSettings["ClientId"].ToString(); to call it up from that file? Calling it as it of course does not work as it is looking for it in web.config.
I do not want to put the appSettings in the web.config file. Is that allowed?

You can reference your stores.config file from web.config
<configuration>
<appSettings file="stores.config">
</appSettings>
<configuration>
Your stores.config file should have the following structure:
<appSettings>
<add key="ClientId" value="127605460617602"/>
<add key ="RedirectUrl" value="http://localhost:49548/Redirect.aspx"/>
</appSettings>
Alternatively you can also use:
ConfigurationManager.OpenMappedExeConfiguration Method (ExeConfigurationFileMap, ConfigurationUserLevel)
For example:
// Map the new configuration file.
var configFileMap = new ExeConfigurationFileMap();
configFileMap.ExeConfigFilename = "stores.config";
// Get the mapped configuration file
var config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
var clientid = config.AppSettings["ClientId"];

Related

Read separate web.config file outside the application folder

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

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 change the content of my app.config after installation of the application

I am working on WPF application that soon has to be ready for installation but there is a functionallity that allows the user to make changes to the app.config file and I don't know how to do that from the code-behind of the application.Also I don't know how this is going to work after the installation of the app.
Simply said: I have a window that allows the user to enter a text that is going to be searched for in the web.config of another application.So in my app.config I have a different searches and I want after the installation the user to be able (after entering values in the window's textoxes) enter new values in the app.config of the application.
Can somebody tell if that is possible and eventually how I could achieve this?
How I did in my application. I have app.config as following
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="StoreConnectionString"
connectionString="Data Source=.\;MultipleActiveResultSets=True;Initial Catalog=Store;Integrated Security=False;"
providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
<add key="ExportPath" value="D:\" />
<add key="CompanyName" value="My Company" />
<add key="mail" value="email#mail.com" />
<add key="phone" value="+992918254040" />
<add key="ExpDate" value="Pink" />
<add key="Print" value="No" />
<add key="EnforcePassw" value="Yes"/>
</appSettings>
</configuration>
So I can change and save app Settings from my application, here is code
private void btnSave(object sender, RoutedEventArgs e)
{
//returns path of folder where your application is
string appPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
//combines path of folder and file
string configFile = System.IO.Path.Combine(appPath, "MyApp.exe.config");
//Defines the configuration file mapping for an .exe application
ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();
configFileMap.ExeConfigFilename = configFile;
System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
config.AppSettings.Settings["ExportPath"].Value = txtExport.Text;
config.AppSettings.Settings["CompanyName"].Value = txtComapny.Text;
config.AppSettings.Settings["mail"].Value = txtEmail.Text;
config.AppSettings.Settings["phone"].Value = txtPhone.Text;
config.AppSettings.Settings["Print"].Value = print;
config.AppSettings.Settings["EnforcePassw"].Value = password;
config.AppSettings.Settings["ExpDate"].Value = color;
config.Save();
}
Hope it will be help you!
If you want to add new strings use this code;
config.AppSettings.Settings.Add("Key", "Value");
this may be helpful
Configuring Application/User Settings in WPF the easy way.

Count the no of keys in appconfig in a class file

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

My config file for dll or why cannot parse Section..?

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.

Categories

Resources