Edit app.config file and read settings - c#

I have a app.config file.
I have settings there.
I want to modify settings after my build and then read it from file.
I mean I want to change settings by edeting a file.
I know how to change settings programmaticaly but I need it by editing file.
No I'm trying to do so:
private void ReadSettings()
{
string appPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
string settingsPath = Path.Combine(appPath, "app.config");
ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();
configFileMap.ExeConfigFilename = settingsPath;
System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
string value=config.AppSettings.Settings["Type"].Value;
}
My settings:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="RxTest.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
</configSections>
<userSettings>
<MyApp.Properties.Settings>
<setting name="Type" serializeAs="String">
<value>document</value>
</setting>
</RxTest.Properties.Settings>
</userSettings>
</configuration>
Problem is that there is nothing in Settings property.
What shuld I do to read settings from edeted file?

The UserSettings written in your app.config file should be automatically added into it by adding an entry into your properties.
You can achieve getting the values from your properties like this:
string value = Properties.Settings.Default.Type;
EDIT I:
To be sure you always have the freshest value, you can either refresh a section:
ConfigurationManager.RefreshSection(sectionName);
Or you can reaload the file:
Properties.Settings.Default.Reload();

Related

Accessing Settings in different ways

I have a new (test) console application that I'm trying to access the settings.
When I attempt to access it this way, from what I've read on SO and other places, this should work:
var test1 = System.Configuration.ConfigurationManager.AppSettings["MySetting"];
but it doesn't, it returns null.
When I do it this way, it works fine:
var test2 = Properties.Settings.Default.MySetting;
Why doesn't the first one work? Everything I've read shows to use it the first way.
Am I using it incorrectly?
EDIT
In response to Mason.
I'm confused on your comment. The app.config is where the setting is being set from the properties of the application:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="ConsoleApp1.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6" />
</startup>
<applicationSettings>
<ConsoleApp1.Properties.Settings>
<setting name="MySetting" serializeAs="String">
<value>testtesttest</value>
</setting>
</ConsoleApp1.Properties.Settings>
</applicationSettings>
</configuration>
System.Configuration.ConfigurationManager.AppSettings is for reading settings from the app.config or web.config files (for ASP.NET). It does not read from the settings files.
Because AppSettings refers to reading the settings in MyApp.config

How to read an App.Config of a different application in C#

I have a console application written in C# which uses an app.config file. This application is intended to be run on a server using the task scheduler. Now I want to develop a UI that reads and writes from and to the app.config. (Note that this config is not intended to replace the config file of the UI application.)
But I'm struggling to read the settings from the file. Using the ConfigurationManager I'm able to open the config file, BUT I cannot access the configuration settings.
This is the sample config file generated by Visual Studio (2010):
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="AccessingConfigSample.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
</configSections>
<userSettings>
<AccessingConfigSample.Properties.Settings>
<setting name="ApplicationTitle" serializeAs="String">
<value>Accessing Config files</value>
</setting>
<setting name="VersionNo" serializeAs="String">
<value>V 1.0</value>
</setting>
</AccessingConfigSample.Properties.Settings>
</userSettings>
</configuration>
After consulting several article on stackoverflow, I tried this to open the file and access the user section:
if (File.Exists(configFile))
{
var configMap = new ExeConfigurationFileMap{ ExeConfigFilename = configFile};
var config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
var userSection = config.GetSection("userSettings");
}
I tried this as well:
var userSection = config.GetSection("AccessingConfigSample.Properties.Settings");
Both returned null.
So what am I doing wrong here?
Any help or hints are highly appreciated!
The config file you use as an example is using a ConfigurationSectionGroup and those need to be read with the matching method GetSectionGroup on the Configuration element instead of GetSection
The following code snippet does output the content of the SectionGroup to the Debug console:
if (File.Exists(configFile))
{
var configMap = new ExeConfigurationFileMap { ExeConfigFilename = configFile };
var config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
// get the sectionGroup!
var userSectionGroup = config.GetSectionGroup("userSettings");
foreach (var userSection in userSectionGroup.Sections)
{
// check for a ClientSettingSection
if (userSection is ClientSettingsSection)
{
// cast from ConfigSection to a more specialized type
var clientSettingSect = (ClientSettingsSection) userSection;
foreach (SettingElement clientSetting in clientSettingSect.Settings)
{
Debug.WriteLine(String.Format("{0}={1}", clientSetting.Name, clientSetting.Value.ValueXml.InnerText ));
}
}
}
}
Notice that I cast the object instance to a ClientSettingSection to retrieve the settings value (which is a SettingElement).
If you put this to work with the sample config you provided the result in the Debug Output Window pane should be:
ApplicationTitle=Accessing Config files
VersionNo=V 1.0

ConfigurationManager not loading settings

Note: I am new to ConfigurationManager and .NET in general.
I have:
static void Main(string[] args) {
//...
String path = ConfigurationManager.AppSettings["training_path"];
StreamReader sr = new StreamReader(path) // path always null
}
I added...
Console.WriteLine(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
...to the top of main, and it outputs the expected default configuration file.
The configuration file looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="xgboost_format.Application" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<applicationSettings>
<myApp.Application>
<setting name="training_path" serializeAs="String">
<value>C:\test.csv</value>
</setting>
</myApp.Application>
</applicationSettings>
</configuration>
The issue is that the path setting is always null. I get a System.ArgumentNullException when calling new StreamReader(path).
How can I access the settings?
You can do it with (double-check the namespace is matching to whatever you have in your application):
String path = myApp.Application.Properties.Settings.Default.path;
You can also read Using Application Settings and User Settings which goes into more details about design-time settings.
Try this -
<appSettings>
<add key="training_path" value="C:\test.csv" />
</appSettings>

How to save value for key in *config file

Try to store and to read some user definde value to *.config file
Code for reading from file
public int GetVolumeFromConfigFile()
{
return Convert.ToInt32(ConfigurationManager.AppSettings["Volume"]);
}
Works perfect
Try to update existing key with this
public int SetVolumeFromConfigFile()
{
ConfigurationManager.AppSettings["Volume"] = "10";
}
Got error - file only for reading, change for something like this:
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
config.AppSettings.Settings.Add(label.Text.ToString(), box.Value.ToString());
config.Save(ConfigurationSaveMode.Minimal);
Got no errors, but nothing changed in file.
My *.config file is :
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="PlayDemo.SettingsPlayIt" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<userSettings>
<PlayDemo.SettingsPlayIt>
<setting name="Volume" serializeAs="String">
</setting>
</PlayDemo.SettingsPlayIt>
</userSettings>
Just try to understand where I'm wrong
Here it is
Configuration config = ConfigurationManager.OpenExeConfiguration(System.Windows.Forms.Application.ExecutablePath);
config.AppSettings.Settings["Volume"].Value = "10";
config.Save(ConfigurationSaveMode.Modified);
This won't update the App.config in your project in Visual Studio, but the "ExecutableName".config in the bin folder of your project.

Changing section name in app.config - causes ConfigurationException

I have a WinForms application that I have changed the name of. I've changed the name everywhere I can find it, and can find no traces of the old name (except as below) and everything works fine; the one exception is in app.config, where if I change OLDNAME to NEWNAME any attempt to read any of the configuration settings throws a ConfigurationExceptioon of "Configuration system not ready", if I recall correctly.
Can anyone suggest how I can change the OLDNAME below to something else, such as my new name, without upsetting the config system?
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="OLDNAME.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
</configSections>
<userSettings>
<OLDNAME.Properties.Settings>
<setting name="MainWindowPosition" serializeAs="String">
<value>0, 0, 0, 0</value>
</setting>
<setting name="UseShortDeviceNames" serializeAs="String">
<value>False</value>
</setting>
</OLDNAME.Properties.Settings>
</userSettings>
</configuration>
The link http://www.codeproject.com/Articles/10981/Understanding-Section-Handlers-App-config-File will explain more using Section Handlers for config.
You must change alsow the section name, you section name is linked to the projects where is build and you have two posibility:
- rename the project (output) and in app.config
- create a new custom group and use the settings

Categories