One of the most common ways to store application setting is in the config file. Below I will show examples of how to store configurations and their retrieval.
AppSettings and ConnectionString Sections
Include the appSettings and/or connectionStrings sections in .config file for retrieval from your application.
<?xml version="1.0" encoding="utf-8"?> <configuration> <appSettings> <add key="MySampleKey" value="Sample value" /> </appSettings> <connectionStrings> <add name="DataSource" connectionString="Server=MyDevServer;Database=Northwind; Integrated Security=true;" providerName="System.Data.SqlClient"/> </connectionStrings> </configuration>
C# code for getting the values
var appsettingValue = ConfigurationManager.AppSettings.Get("MySampleKey"); var connectionStringValue = ConfigurationManager.ConnectionStrings["DataSource"] .ConnectionString;
Storing config settings in separate files
When working with large applications, your config files can get very large as well. To break your configurations into smaller, more manageable pieces, you can separate them into individual files and call them from the main configurations file.
For all the individual configuration files, set “Copy to Output Directory” = “Copy Always”. Look under properties. I like to keep each config file in a separate folder named config.
<?xml version="1.0" encoding="utf-8"?> <configuration> <appSettings configSource=".\config\MySampleApp.AppSettings.config" /> <connectionStrings configSource=".\config\MySampleApp.ConnectionStrings.config" /> </configuration>
MySampleApp.AppSettings.config
<?xml version="1.0" encoding="utf-8"?> <appSettings> <add key="MySampleKey" value="Sample value" /> </appSettings>
MySampleApp.ConnectionStrings.config
<?xml version="1.0" encoding="utf-8"?> <connectionStrings> <add name="DataSource" connectionString="Server=MyDevServer;Database=Northwind; Integrated Security=true;" providerName="System.Data.SqlClient"/> </connectionStrings>
Storing config settings in the Windows Registry
To simplify deployment without using transformations, you can instead use the Registry to store configuration settings that will be unique to each machine. The value of the key is prefixed with registry and is then used by a AppConfigReader class to get the value stored in the registry.
Sample Registry settings:
Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SOFTWARE\Company\MySampleApp] "MySampleKey"="Sample value" "DataSource"="Server=MyDevServer;Database=Northwind;Integrated Security=true;"
Settings to retrieve from the registry
<appSettings> <add key="MySampleKey" value="registry:HKLM\Software\Company\MySampleApp,MySampleKey" /> </appSettings>
<connectionStrings> <add name="DataSource" connectionString="registry:HKLM\Software\Company\MySampleApp,DataSource" providerName="System.Data.SqlClient"/> </connectionStrings>
C# code using AppConfigReader
var mySampleValue = AppConfigReader.GetAppSetting("MySampleKey"); var myConnectionValue = AppConfigReader.GetConnectionSetting("DataSource");
AppConfigReader class for retrieving registry values
using System; using System.ComponentModel; using System.Configuration; using Microsoft.Win32; public static class AppConfigReader { private const string SemiColonDelimiter = ";"; private const string ColonDelimiter = ":"; private const string CommaDelimiter = ","; private const string RegistryPrefix = "registry:"; private const string UnderScore = "_"; private const string BackslashDelimiter = "\\"; public static string GetAppSetting(string appSettingName) { string settingValue = ConfigurationManager.AppSettings[appSettingName]; if (settingValue == null) { throw new ArgumentNullException("Not found in appsettings section"); } string regValue = GetRegistryString(settingValue); if (regValue == null) { throw new ArgumentNullException("Not found in registry"); } return regValue; } public static string GetConnectionSetting(string appSettingName) { var settingValue = ConfigurationManager.ConnectionStrings[appSettingName]; if (settingValue == null) { throw new ArgumentNullException("Not found in connection section"); } string regValue = GetRegistryString(settingValue.ConnectionString); if (regValue == null) { throw new ArgumentNullException("Not found in registry"); } return regValue; } /// Receives a string in the format: /// registry:HKLM\Software\ASP.NET\MyKey\ASPNET_SETREG,sqlConnectionString /// and pulls the value from the correct registry hive public static string GetRegistryString(string configSetting) { if (string.IsNullOrWhiteSpace(configSetting)) { throw new ArgumentNullException("configSetting is empty"); } if (configSetting.StartsWith(RegistryPrefix, StringComparison.OrdinalIgnoreCase)) { string regKeyPathAndKey = configSetting .Split(ColonDelimiter.ToCharArray())[1].Trim(); string regKeyPath = regKeyPathAndKey .Split(CommaDelimiter.ToCharArray())[0].Trim(); string keyName = regKeyPathAndKey .Split(CommaDelimiter.ToCharArray())[1].Trim(); RegistryKey regkeyHive; //// Open the proper Registry Hive if (regKeyPath.StartsWith("HKLM", StringComparison.OrdinalIgnoreCase)) { regkeyHive = Registry.LocalMachine; } else if (regKeyPath.StartsWith("HKCR", StringComparison.OrdinalIgnoreCase)) { regkeyHive = Registry.ClassesRoot; } else if (regKeyPath.StartsWith("HKCU", StringComparison.OrdinalIgnoreCase)) { regkeyHive = Registry.CurrentUser; } else if (regKeyPath.StartsWith("HKU", StringComparison.OrdinalIgnoreCase)) { regkeyHive = Registry.Users; } else if (regKeyPath.StartsWith("HKCC", StringComparison.OrdinalIgnoreCase)) { regkeyHive = Registry.Users; } else { throw new ArgumentNullException("{0}; Unknown Key reference: {1}", configSetting, regKeyPath); } int seperatorPosition = regKeyPath.IndexOf(BackslashDelimiter, 0, System.StringComparison.Ordinal) + 1; regKeyPath = regKeyPath.Substring(seperatorPosition, regKeyPath.Length - seperatorPosition); RegistryKey regKey = regkeyHive.OpenSubKey(regKeyPath); if (regKey == null) { throw new ArgumentNullException( "Attempt to get undefined registry key for {0} {1} {2}", regkeyHive.Name, regKeyPath, keyName); } return (string)regKey.GetValue(keyName); } else { // return the Config string, registry not specified return configSetting; } } }
Speak Your Mind