Cannot write settings on app.config (or no changes are shown) - c#

I'm creating an application on .net framework 4.5
whenever i want to load the app config values (appSettings section) and write the changes, i don't see my changes if i refresh the section. What i am doing wrong? and how can i solve it?
code
private void LoadConfig()
{
NameValueCollection appSettings = ConfigurationManager.AppSettings;
for (int i = 0; i < appSettings.Count; i++)
{
switch (appSettings.GetKey(i))
{
case "initialCatalog":
txtInitialCatalog.Text = appSettings.GetValues(i)[0];
break;
case "dataSource":
txtDatasource.Text = appSettings.GetValues(i)[0];
break;
case "userName":
txtUsername.Text = appSettings.GetValues(i)[0];
break;
case "password":
txtPassword.Text = appSettings.GetValues(i)[0];
break;
case "portalUrl":
txtUrl.Text = appSettings.GetValues(i)[0];
break;
}
}
}
private void SaveConfig()
{
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
KeyValueConfigurationCollection appSettings = config.AppSettings.Settings;
appSettings["initialCatalog"].Value = txtInitialCatalog.Text;
appSettings["dataSource"].Value = txtDatasource.Text;
appSettings["userName"].Value = txtUsername.Text;
appSettings["password"].Value = txtPassword.Text;
appSettings["portalUrl"].Value = txtUrl.Text;
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
}
App.config file
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<appSettings>
<add key="initialCatalog" value="a" />
<add key="dataSource" value="b" />
<add key="password" value="c" />
<add key="userName" value="d" />
<add key="portalUrl" value="e" />
<add key="poolingTime" value="60000" />
<add key="ClientSettingsProvider.ServiceUri" value="" />
</appSettings>
i call ReadConfig() when the forms is Activated and save the data when a button is pressed (Ok or Apply) i close the application i rerun it but no changes are made to the app.config file
any ideas???

I think what is happening is that you are testing in Visual Studio, it copys the App.Config to your Debug/Release directory and renames it YourApplication.vshost.exe.config which gets reset each time you start your application. Try running the executable outside of Visual Studio which will use the YourApplication.exe.config file and see if that works for you. Your Code is working for me and retaining your changes on application restart if I run it outside of Visual Studio.

usually, I do this:
...
config.AppSettings.Settings.Remove("TextBoxNumber");
config.AppSettings.Settings.Add("TextBoxNumber", "");
It works fine. I guess it is because one of your key is not in the app.config yet. You need Remove/Add it (like the above code), or, create the key in the app.config first.
====================
Update
Try this:
config.AppSettings.Settings["initialCatalog"].Value = txtInitialCatalog.Text;
instead of
appSettings["initialCatalog"].Value = txtInitialCatalog.Text;
Any difference?

Related

Displaying and modifying xml data with C#

New to C# programming, and I'm kind of stuck right now. How would I create a simple program that let's me extract and display the data source value in connectionStrings. And lets me modify the Id and password? Am I on the right track with parsing
Document X = XDocument.Load("C:\Users\Odd_Creature\Desktop\SecureConfig\\UserProfiles\UserInfo.exe.config")
var configuration= X.Element("configuration").Element("connectionStrings");
var location = configuration.Descendants("").Attributes("").FirstOrDefault().Value;
doc.Save(xmlfile);
XMLFILE
<configuration>
<configProtectedData />
<system.diagnostics />
<system.windows.forms />
<uri />
<appSettings>
<add key="GenerateProfile" value="true" />
<add key="TestScore" value="30" />
<add key="TestApplicationName" value="User Account" />
</appSettings>
<connectionStrings>
<add name="MyExample.database" connectionString="data source=.\SQLEXPRESS;initial catalog=wadb;integrated security=false;encrypt=true;trustservercertificate=true;User Id=Tester;Password=Test1;"
providerName="System.Data.SqlClient" />
</connectionStrings>
This would be a brute force approach to parsing the connection string from an XML file.
static void Main(string[] args)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("settings.xml");
string connectionStrings = xmlDoc.GetElementsByTagName("connectionStrings")[0].InnerXml;
string tag = "connectionString=\"";
string connectionString = connectionStrings.Substring(connectionStrings.IndexOf(tag) + tag.Length);
string[] tokens = connectionString.Split(';');
Console.WriteLine(tokens.FirstOrDefault(t => t.Contains("data source=")));
Console.WriteLine(tokens.FirstOrDefault(t => t.Contains("User Id=")));
Console.WriteLine(tokens.FirstOrDefault(t => t.Contains("Password=")));
}
And the output would be:
data source=.\SQLEXPRESS
User Id=Tester
Password=Test1
With a little more code, you should be able to edit these fields, and then use xmlDoc.Save() to update your changes.

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");

app.config not updating when I use configmanager

I have these pieces of code:
string theme = ConfigurationManager.AppSettings["Theme"];
private void ChangeTheme(string Name)
{
if(Name=="Light")
{
Form1.ActiveForm.BackColor = System.Drawing.Color.White;
Form.ActiveForm.ForeColor = System.Drawing.Color.Black;
}
if (Name == "Dark")
{
Form1.ActiveForm.BackColor = System.Drawing.Color.Black;
Form.ActiveForm.ForeColor = System.Drawing.Color.DarkOrange;
}
Configuration cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
cfg.AppSettings.Settings["Theme"].Value = Name;
cfg.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
}
My app.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Volume" value="7"/>
<add key="Keyval" value="X"/>
<add key="Theme" value="Light"/>
</appSettings>
</configuration>
Basically, when I press the radio buttons it changes the theme and sends the string to changetheme(), but it does not update in the app.config.
Are you running it in debug?
Probably you are looking at the wrong file. While debugging visual studio uses the config file from the bin\Debug so it would not update the App.config from the solution.
Instead of using == for comparison, I would use the String Equals Method:
Name.Equals("Light")
While I'd bet that it's not the issue, it's good practice and maybe you get lucky and that is the issue.

ConfigurationManager Not saving values as expected

I have a config file for my program as follows
<appSettings>
<add key="ShowDebugWindow" value="false"/>
<add key="AppDataSubFolder" value="DLI\Keymon"/>
<add key="KeymonSettingsFile" value="Keymon.xml"/>
<add key="KeymonSettingsFileExtension" value="XML"/>
</appSettings>
With some digging around I found out how I can A) check if that key exists B) add a new one if needed. Since my program is in Program Files I found out that to avoid having the config file saved to virtual store that I have to have my program run as admin. That is not allowable so I decided to make a console project that would fix this for me. Easy enough.
So i did this
public static int Main(string[] args)
{
FixConfigFile();
return 0;
}
private static void FixConfigFile()
{//warning if the program is writing to a protect area, the config file might be redirected to virtual store
UpdateSettingIfMissing("ShowDebugWindow", "false");
UpdateSettingIfMissing("AppDataSubFolder", "DLI\\Keymon");
UpdateSettingIfMissing("KeymonSettingsFile", "Keymon.xml");
UpdateSettingIfMissing("KeymonSettingsFileExtension", "XML");
UpdateSettingIfMissing("LeftButton1", "");
UpdateSettingIfMissing("RightButton1", "");
UpdateSettingIfMissing("FunctionButton1", "");
UpdateSettingIfMissing("FunctionButton2", "");
UpdateSettingIfMissing("FunctionButton3", "");
UpdateSettingIfMissing("FunctionButton4", "");
UpdateSettingIfMissing("FunctionButton5", "");
UpdateSettingIfMissing("FunctionButton6", "");
}
private static void UpdateSettingIfMissing(string key, string defaultValue)
{
var setting = ConfigurationManager.AppSettings[key];
if (setting == null)
{
UpdateSetting(key, defaultValue);
}
}
private static void UpdateSetting(string key, string value)
{
Configuration configuration = ConfigurationManager.OpenExeConfiguration(#"Keymon.exe");
configuration.AppSettings.Settings.Add(key, value);
configuration.Save(ConfigurationSaveMode.Minimal);
}
The config file then would look like this
<add key="ShowDebugWindow" value="false,false" />
<add key="AppDataSubFolder" value="DLI\Keymon" />
<add key="KeymonSettingsFile" value="Keymon.xml,Keymon.xml" />
<add key="KeymonSettingsFileExtension" value="XML,XML" />
<add key="LeftButton1" value="" />
<add key="RightButton1" value="" />
<add key="FunctionButton1" value="" />
<add key="FunctionButton2" value="" />
<add key="FunctionButton3" value="" />
<add key="FunctionButton4" value="" />
<add key="FunctionButton5" value="" />
<add key="FunctionButton6" value="" />
notice that the value now has "2" values that are comma separated... WHY??? So as a test I deleted all keys, and ran my program. The values are all correct now, but now keymon crashes because the key/values were not loaded. Which is strange because in keymon i run this..
if (RunFixer)
{
System.Diagnostics.Process.Start("KeymonConfigFixer.exe");
ConfigurationManager.RefreshSection("appSettings");
}
So i don't get it. What am I missing? why is it doing this? Help
It's because in UpdateSettingIfMissing you use ConfigurationManager.AppSettings[key] which opens the app settings for the current application (your console app) while in UpdateSetting you open the settings for Keymon.exe

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