I've used the Configuration Section Designer (csd) to generate an xml configuration file to my application.
Now, I want to work with this xml file (on c#) and do 2 things:
1. read a specific value (searching by its field), something like
txtbox_username.Text = ConfigurationManager.AppSettings["userName"];
2. write a specific value, something like
config.AppSettings.Settings["userName"].Value = txtbox_username.Text;
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("configuration");
p.s: this is how i perform read/write for regular xml files that looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
add key="userName" value="Value1"
</appSettings>
</configuration>
but the csd generated xml looks different...
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="sectionName" type="Sample.ConfigurationSection.sectionName, Sample.ConfigurationSection, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
</configSections>
<sectionName xmlns="Sample.ConfigurationSection">
<logFile debugLevel="3" filePath="c:\new" maxFileCount="10" maxFileLength="1000"/>
<results path="C:\Results"/>
<details user="blabla" pass="12345" code="abc"/>
<stuff fromAddress="from#gmail.com" toAddress="to#gmail.com" sendMail="true""/>
</sectionName>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
</configuration>
here, I want to edit and save, for example, user/pass/code fields.
In short (and using these extensions: http://searisen.com/xmllib/extensions.wiki) you can do this to read/write the user,
XElement file = XElement.Load(xmlFile);
XNamespace ns = "Sample.ConfigurationSection";
XElement section = file.GetElement(ns + "sectionName");
string user = section.Get("details/user", string.Empty);
section.Set("details/user", "bubba", true); // true = set as attribute
file.Save(xmlFile);
Related
I have created a console app in c# that reads information from App.config. if i add things in appSettings section, i can acces them and it works, but as soon as i add some custom sections i cant read anything from it. I am using ConfigurationManager, and i have the reference for it included.
My app config looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<appSettings>
<add key="overwriteBackupFiles" value="False"/>
<add key="path" value="c:\temp"/>
</appSettings>
<ImageFormatsINeed>
<add key="type1" value="width=180&height=180"></add>
<add key="type2" value="width=220&height=220"></add>
<add key="type3" value="width=500&height=500"></add>
</ImageFormatsINeed>
</configuration>
and i am trying to acces those information like this:
string path = ConfigurationManager.AppSettings["path"];
var settings = ConfigurationManager.GetSection("ImageFormatsINeed");
When i didnt have the ImageFormatsINeed section i could get the path from AppSettings and it was working. But as soon as i added my ImageFormatsINeed section, everything stops working.
Now my question is how can i add custom sections in app.config that it will work, or should i just read my ImageInformation from some custom xml file or config file?
You have to use the tag <configSections> at the top in your app.config, for this case you should use the type AppSettingsSection
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="ImageFormatsINeed" type="System.Configuration.AppSettingsSection" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<appSettings>
<add key="overwriteBackupFiles" value="False"/>
<add key="path" value="c:\temp"/>
</appSettings>
<ImageFormatsINeed>
<add key="type1" value="width=180&height=180"></add>
<add key="type2" value="width=220&height=220"></add>
<add key="type3" value="width=500&height=500"></add>
</ImageFormatsINeed>
</configuration>
Then in your C# code:
NameValueCollection settings_section = ConfigurationManager.GetSection("ImageFormatsINeed") as NameValueCollection;
Console.WriteLine(settings_section["type1"]);
I have to get string inside Setting-> Value in C#. How to reach there through code and fetch that value from App.config file. Please help me. Thank you.
<?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="MyApplication.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.5" />
</startup>
<applicationSettings>
<MyApplication.Properties.Settings>
**<setting name="ConnectionString" serializeAs="String">
<value>server=127.0.0.1;uid=root;pwd=root;database=MyApplication_db;</
</setting>**
</VASI_Application.Properties.Settings>
</applicationSettings>
</configuration>
You can use the following code:
var section = (ClientSettingsSection)ConfigurationManager.GetSection("applicationSettings/MyApplication.Properties.Settings");
var settingElement = section.Settings.Get("ConnectionString");
var settingValue = settingElement.Value.ValueXml.InnerText;
// settingValue equals "server=127.0.0.1;uid=root;pwd=root;database=MyApplication_db;"
First, you retrieve the ClientSettingsSection section. The name of the section is a combination of the name of the "applicationSettings" section and its inner "MyApplication.Properties.Settings" section. Then, you retrieve the actual settings by calling Settings.Get("ConnectionString") on the returned ClientSettingsSection instance. Finally, you can use the Value.ValueXml.InnerText property of the returned setting to get to the actual value.
By the way, you have two small errors in your XML file:
The <MyApplication.Properties.Settings> element in incorrectly closed with </VASI_Application.Properties.Settings>
The <value> element is not correctly closed with </value>
Don't you have the property ConnectionString?
As documented here, usually you can access it in this way:
var setting = Properties.Settings.Default.ConnectionString;
By the way, your application tag starts with MyApplication.Properties.Settings but ends with VASI_Application.Properties.Settings
If you do actually want to go ahead with a custom config file section like in your example then you will need to follow this Microsoft guide for creating custom configuration sections.
https://msdn.microsoft.com/en-us/library/2tw134k3.aspx
If you get stuck following this guide then raise another question.
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>
Try to save all data in to config file, and then read it and apply to my program during running - as user preference.
Whats done: create new config file (using Add new element-> add congif file). In this file put simple code
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSetting>
<add Key="Volume" value="100" />
</appSetting>
</configuration>
After it create method
public int GetVolumeFromConfigFile()
{
return Convert.ToInt32(ConfigurationManager.AppSettings.Get("Volume"));
}
and in main programm call it like
Value = (MyClass.GetVolumeFromConfigFile());
But it's not work. (During debaggin it's return nothing)
Think it can be few reason:
I need to add (I don't now in what way) what config file to use, because i have few files *.config - one as default (App.exe.config, and another - that i created)
I use incorrect method to get value from config file
Also I read about some another way to store app settings, like store it in *.settings file
What I'm doing wrong and what method prefered?
Additional information - use net 4.0
EDIT
Remove my config file, and add to existed few lines (in strong>)
<?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">
<value>10</value>
</setting>
</PlayDemo.SettingsPlayIt>
</userSettings>
Here I add my key
<appSetting>
<add key="Volume" value="100" />
</appSetting>
</configuration>
try this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Volume" value="100" />
</appSettings>
</configuration>
and
return Convert.ToInt32(ConfigurationManager.AppSettings["Volume"]);
the appSettings are key value pairs, so you can access it like you would a value in a Dictionary
If you want to use a separate config file, try this:
Dim config As System.Configuration.Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
config.AppSettings.File = "yourFileName"'tell Configuration what file to read
config.Save(ConfigurationSaveMode.Modified) ' save the Configuration setting
ConfigurationManager.RefreshSection("appSettings") ' update just the <appSettings> node
I really like the following technique, using ConfigurationSection. This allows you for painless manipulation of your configuration. But it is more specific upfront.
http://msdn.microsoft.com/en-us/library/2tw134k3%28v=vs.90%29.aspx
Following config file causes error because of & in 'url' value:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key ="url" value ="http://www.example.com/?user=admin&password=1234"/>
</appSettings>
</configuration>
The question is which encoding to use for key/value in a config file ? (i.e Url Encoding ...)
This is an XML file. As such, you must XML-escape all reserved characters:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key ="url" value ="http://www.example.com/?user=admin&password=1234"/>
</appSettings>
</configuration>
Programmatically you can perform this type of escaping using the System.Web.HttpUtility.HtmlEncode method. Yes, its name suggests HTML specific encoding, but in my experience this is equivalent to XML escaping.