Deserialize the xml configuration file present in different location - c#

I am trying to Deserialize XML configuration file stored in %LOCALAPPDATA%\Configuration\Configuration.XML. I want to read the key value section and store it in the local variable.
The XML file looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="FolderPath" value="C:\\Data" />
<add key="Name" value="xxx" />
<add key="Type" value="xxx" />
</appSettings>
</configuration>
ConfigurationManager.Appsettings.Get("FolderPath") does not work because the xml file is in the different location.
So I tried with the following code, which does not work.
var configFile = Path.Combine(Environment.GetEnvironmentVariable("LocalAppData"), "Configuration", "Configuration.XML")
var configuration = ConfigurationManager.OpenExeConfiguration(configFile);
var appSettings = configuration.GetSection("appSettings").SectionInformation;
Please help me to read the configuration.XML as shown above.
Thank you.

Thanks for your suggestions #jdweng.
I was able to solve the issue
var configFile = Path.Combine(Environment.GetEnvironmentVariable("LOCALAPPDATA"), "Configuration", "Configuration.XML"));
if (File.Exists(configFile))
{
ConfigurationDetails = new Dictionary<string, string>();
XDocument doc = XDocument.Load(configFile);
var elements = doc.Descendants("add");
foreach (var element in elements)
{
ConfigurationDetails.Add(element.Attribute("key").Value, element.Attribute("value").Value);
}
}

Related

C# XmlElement: Why does it always return Nulll?

I'm relatively new to C#, and just started using XmlElement and the SingleNode Method. For some reason "customSettings" keeps returning null, although the XML Document is being loaded correctly. I've checked that by loading it as a string. I've tried everything i could imagine so far including the attempt in the comment. Any help or suggestions are much appreciated. Here is my XML Doc:
EDIT: works with solution from CodingYoshi, but is there a better way?
EDIT: changed XML and code for NSGaga to resolve read only exception with NameValueCollection in user.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="users_fächer" type="System.Configuration.NameValueSectionHandler" />
</configSections>
<users_faecher>
<add key="user1" value="value1" />
<add key="user2" value="value2" />
</users_faecher>
</configuration>
Code:
string dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"Users.config");
string new_fächer = input[1];
ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();
configMap.ExeConfigFilename = dir;
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
ConfigurationSection myParamsSection = config.GetSection("users_faecher");
string myParamsSectionRawXml = myParamsSection.SectionInformation.GetRawXml();
XmlDocument sectionXmlDoc = new XmlDocument();
sectionXmlDoc.Load(new StringReader(myParamsSectionRawXml));
NameValueSectionHandler handler = new NameValueSectionHandler();
NameValueCollection users_fächer = handler.Create(null, null, sectionXmlDoc.DocumentElement) as NameValueCollection;
users_fächer.Set(user, new_fächer);
config.Save(ConfigurationSaveMode.Modified, true);
This will get you the first add element:
doc.ChildNodes[0].NextSibling.ChildNodes[1].ChildNodes[0].ChildNodes[0];
This will get you the first add element's value attribute.
doc.ChildNodes[0].NextSibling.ChildNodes[1]
.ChildNodes[0].ChildNodes[0].Attributes["value"].Value;

Updating/removing entries from appSettings

I am trying to update configuration files from other projects than the one I'm in.
The UpdateConfig() works fine, but the DeleteFromConfig() doesn't remove the entry.
Let's say I have an entry like this:
add key="someKey" value="oldValue" /
DeleteFromConfig() leaves the entry as before, but if I comment out the Remove line from UpdateConfig and try to change the value to 'newValue'it gives me this:
add key="someKey" value="oldValue,newValue" /
The AppSettings.Settings.Remove(key) line only removes the value, not the entire entry.
Is there a way to remove the whole thing?
private void UpdateConfig(string path, string key, string value)
{
Configuration config = ConfigurationManager.OpenExeConfiguration(path);
config.AppSettings.Settings.Remove(key);
config.AppSettings.Settings.Add(key, value);
config.Save(ConfigurationSaveMode.Modified);
}
private void DeleteFromConfig(string path, string key)
{
Configuration config = ConfigurationManager.OpenExeConfiguration(path);
config.AppSettings.Settings.Remove(key);
config.Save(ConfigurationSaveMode.Modified);
}
Delete the key1 from config using XmlDocument
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="key1" value="3" />
<add key="key2" value="1" />
</appSettings>
</configuration>
var xmlDoc = new XmlDocument();
xmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
XmlNode keyNode1 = xmlDoc.SelectSingleNode("//appSettings/add[#key='key1']");
keyNode1.ParentNode.RemoveChild(keyNode1);
xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
ConfigurationManager.RefreshSection("appSettings");

AppSettings from custom files

I am struggling with the configuration and setting classes in .NET 2.0
If the following is contaned in a file called app.config
<config>
<appSettings>
<add key="Foo" value="Hello World!"/>
</appSettings>
</config>
I know I can access the appSetting by
// this returns "Hello World!"
ConfigurationManager.AppSettings["Foo"]
However if the file is called app1.config (or any other name) I cannot access the appSetting.
As long as I understand, with ConfigurationManager.OpenExeConfiguration I should read custom config setting files.
Configuration conf = ConfigurationManager.OpenExeConfiguration(#"..\..\app1.config");
// this prints an empty string.
Console.WriteLine(conf.AppSettings.Settings["Foo"]);
However conf.AppSettings.Settings["Foo"] returns an empty string.
I have also tried the following code but no success
ExeConfigurationFileMap exeFileMap = new ExeConfigurationFileMap();
exeFileMap.ExeConfigFilename = System.IO.Directory.GetCurrentDirectory()
+ "\\App1.config";
Configuration myConf = ConfigurationManager.OpenMappedExeConfiguration
(exeFileMap, ConfigurationUserLevel.None);
// returns empty string as well
Console.WriteLine(myConf.AppSettings.Settings["Foo"]);
How to read setting from a file not called app.config?
I have created custom file myCustomConfiguration and changes its property Copy to Output Directory to true
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Foo" value="Hello World!"/>
</appSettings>
</configuration>
In CS file
static void Main(string[] args)
{
var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "myCustomConfiguration.config");
Dictionary<string, string> dictionary = GetNameValueCollectionSection("appSettings", filePath);
//To get your key do dictionary["Foo"]
Console.WriteLine(dictionary["Foo"]);
Console.ReadLine();
}
private static Dictionary<string, string> GetNameValueCollectionSection(string section, string filePath)
{
var xDoc = new XmlDocument();
var nameValueColl = new Dictionary<string, string>();
var configFileMap = new ExeConfigurationFileMap { ExeConfigFilename = filePath };
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
string xml = config.GetSection(section).SectionInformation.GetRawXml();
xDoc.LoadXml(xml);
XmlNode xList = xDoc.ChildNodes[0];
foreach (XmlNode xNodo in xList.Cast<XmlNode>().Where(xNodo => xNodo.Attributes != null))
{
nameValueColl.Add(xNodo.Attributes[0].Value, xNodo.Attributes[1].Value);
}
return nameValueColl;
}
Although this is working but I am also looking for better approach.
You should make use of a Settings-File, it's way more comfortable to use, has save and load methods and you can name it what ever you want. Eg. my Settings-File is called "EditorSettings.settings" and I access its properties like this:
MyNamespace.MyProject.EditorSettings.Default.MyProperty1

Reading custom configuration section's key values in C#

I need to read key values from custom sections in app/web.config.
I went through
Reading a key from the Web.Config using ConfigurationManager
and
How can I retrieve list of custom configuration sections in the .config file using C#?
However, they do not specify how to read a custom section when we need to explicitly specify the path to the configuration file (in my case, the configuration file is not in it's default location)
Example of my web.config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<MyCustomTag>
<add key="key1" value="value1" />
<add key="key2" value="value2" />
</MyCustomTag>
<system.web>
<compilation related data />
</system.web>
</configuration>
in which i need to read key value pairs inside MyCustomTag.
When i try (configFilePath is the path to my configuration file):-
var configFileMap = new ExeConfigurationFileMap { ExeConfigFilename = configFilePath };
var config =
ConfigurationManager.OpenMappedExeConfiguration(
configFileMap, ConfigurationUserLevel.None);
ConfigurationSection section = config.GetSection(sectionName);
return section[keyName].Value;
I get a error stating "Cannot access protected internal indexer 'this' here" at section[keyName]
Unfortunately, this is not as easy as it sounds. The way to solve the problem is to get file config file with ConfigurationManager and then work with the raw xml. So, I normally use the following method:
private NameValueCollection GetNameValueCollectionSection(string section, string filePath)
{
string file = filePath;
System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument();
NameValueCollection nameValueColl = new NameValueCollection();
System.Configuration.ExeConfigurationFileMap map = new ExeConfigurationFileMap();
map.ExeConfigFilename = file;
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
string xml = config.GetSection(section).SectionInformation.GetRawXml();
xDoc.LoadXml(xml);
System.Xml.XmlNode xList = xDoc.ChildNodes[0];
foreach (System.Xml.XmlNode xNodo in xList)
{
nameValueColl.Add(xNodo.Attributes[0].Value, xNodo.Attributes[1].Value);
}
return nameValueColl;
}
And the call of the method:
var bla = GetNameValueCollectionSection("MyCustomTag", #".\XMLFile1.xml");
for (int i = 0; i < bla.Count; i++)
{
Console.WriteLine(bla[i] + " = " + bla.Keys[i]);
}
The result:
Formo makes it really easy, like:
dynamic config = new Configuration("customSection");
var appBuildDate = config.ApplicationBuildDate<DateTime>();
See Formo on Configuration Sections

AppSettings get value from .config file

I'm not able to access values in configuration file.
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var clientsFilePath = config.AppSettings.Settings["ClientsFilePath"].Value;
// the second line gets a NullReferenceException
.config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<!-- ... -->
<add key="ClientsFilePath" value="filepath"/>
<!-- ... -->
</appSettings>
</configuration>
Do you have any suggestion what should I do?
This works for me:
string value = System.Configuration.ConfigurationManager.AppSettings[key];
The answer that dtsg gave works:
string filePath = ConfigurationManager.AppSettings["ClientsFilePath"];
BUT, you need to add an assembly reference to
System.Configuration
Go to your Solution Explorer and right click on References and select Add reference. Select the Assemblies tab and search for Configuration.
Here is an example of my App.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<appSettings>
<add key="AdminName" value="My Name"/>
<add key="AdminEMail" value="MyEMailAddress"/>
</appSettings>
</configuration>
Which you can get in the following way:
string adminName = ConfigurationManager.AppSettings["AdminName"];
Give this a go:
string filePath = ConfigurationManager.AppSettings["ClientsFilePath"];
Read From Config :
You'll need to add a reference to Config
Open "Properties" on your project
Go to "Settings" Tab
Add "Name" and "Value"
Get Value with using following code :
string value = Properties.Settings.Default.keyname;
Save to Config :
Properties.Settings.Default.keyName = value;
Properties.Settings.Default.Save();
I am using:
ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();
//configMap.ExeConfigFilename = #"d:\test\justAConfigFile.config.whateverYouLikeExtension";
configMap.ExeConfigFilename = AppDomain.CurrentDomain.BaseDirectory + ServiceConstants.FILE_SETTING;
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
value1 = System.Configuration.ConfigurationManager.AppSettings["NewKey0"];
value2 = config.AppSettings.Settings["NewKey0"].Value;
value3 = ConfigurationManager.AppSettings["NewKey0"];
Where value1 = ... and value3 = ... gives null and value2 = ... works
Then I decided to replace the internal app.config with:
// Note works in service but not in wpf
AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", #"d:\test\justAConfigFile.config.whateverYouLikeExtension");
ConfigurationManager.RefreshSection("appSettings");
string value = ConfigurationManager.AppSettings["NewKey0"];
Using VS2012 .net 4
In the app/web.config file set the following configuration:
<configuration>
<appSettings>
<add key="NameForTheKey" value="ValueForThisKey" />
...
...
</appSettings>
...
...
</configuration>
then you can access this in your code by putting in this line:
string myVar = System.Configuration.ConfigurationManager.AppSettings["NameForTheKey"];
*Note that this work fine for .net4.5.x and .net4.6.x; but do not work for .net core.
Best regards:
Rafael
Coming back to this one after a long time...
Given the demise of ConfigurationManager, for anyone still looking for an answer to this try (for example):
AppSettingsReader appsettingsreader = new AppSettingsReader();
string timeAsString = (string)(new AppSettingsReader().GetValue("Service.Instance.Trigger.Time", typeof(string)));
Requires System.Configuration of course.
(Editted the code to something that actually works and is simpler to read)
See I did what I thought was the obvious thing was:
string filePath = ConfigurationManager.AppSettings.GetValues("ClientsFilePath").ToString();
While that compiles it always returns null.
This however (from above) works:
string filePath = ConfigurationManager.AppSettings["ClientsFilePath"];
Some of the Answers seems a little bit off IMO Here is my take circa 2016
<add key="ClientsFilePath" value="filepath"/>
Make sure System.Configuration is referenced.
Question is asking for value of an appsettings key
Which most certainly SHOULD be
string yourKeyValue = ConfigurationManager.AppSettings["ClientsFilePath"]
//yourKeyValue should hold on the HEAP "filepath"
Here is a twist in which you can group together values ( not for this question)
var emails = ConfigurationManager.AppSettings[ConfigurationManager.AppSettings["Environment"] + "_Emails"];
emails will be value of Environment Key + "_Emails"
example : jack#google.com;thad#google.com;
For web application, i normally will write this method and just call it with the key.
private String GetConfigValue(String key)
{
return System.Web.Configuration.WebConfigurationManager.AppSettings[key].ToString();
}
Open "Properties" on your project
Go to "Settings" Tab
Add "Name" and "Value"
CODE WILL BE GENERATED AUTOMATICALLY
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup ..." ... >
<section name="XX....Properties.Settings" type="System.Configuration.ClientSettingsSection ..." ... />
</sectionGroup>
</configSections>
<applicationSettings>
<XX....Properties.Settings>
<setting name="name" serializeAs="String">
<value>value</value>
</setting>
<setting name="name2" serializeAs="String">
<value>value2</value>
</setting>
</XX....Properties.Settings>
</applicationSettings>
</configuration>
To get a value
Properties.Settings.Default.Name
OR
Properties.Settings.Default["name"]
ConfigurationManager.RefreshSection("appSettings")
string value = System.Configuration.ConfigurationManager.AppSettings[key];
Or you can either use
string value = system.configuration.ConfigurationManager.AppSettings.Get("ClientsFilePath");
//Gets the values associated with the specified key from the System.Collections.Specialized.NameValueCollection
You can simply type:
string filePath = Sysem.Configuration.ConfigurationManager.AppSettings[key.ToString()];
because key is an object and AppSettings takes a string
My simple test also failed, following the advice of the other answers here--until I realized that the config file that I added to my desktop application was given the name "App1.config". I renamed it to "App.config" and everything immediately worked as it ought.
Updated
ConfigurationManager is outdated, you need to use IConfiguration in the .NET Сore environment (IConfiguration is provided by .NET Core built-in dependency injection).
private readonly IConfiguration config;
public MyConstructor(IConfiguration config)
{
this.config = config;
}
public void DoSomethingFunction()
{
string settings1 = config["Setting1"];
}
In my case I had to throw a ' on either side of the '#System.Configuration.ConfigurationManager.AppSettings["key"]' for it to be read into my program as a string. I am using Javascript, so this was in my tags. Note: ToString() was not working for me.
Do something like this :
string value1 = System.Configuration.ConfigurationManager.AppSettings.Get(0); //for the first key
string value2 = System.Configuration.ConfigurationManager.AppSettings.Get(1); //for the first key

Categories