update app.config file at runtime - c#

I am trying to update the app.config file at runtime. I get the error
System.NullReferenceException: object reference not set to an instance of an object. line 59.
What I am trying to do is change the url at runtime, by having a pop up form which has a textbox which is used for the url, this is then used to update the config file.
public void changeSettings()
{
Configuration config =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
KeyValueConfigurationCollection settings = config.AppSettings.Settings;
try
{
Console.WriteLine("nothing " + ConfigurationManager.AppSettings["client_postCodeRef_Service"]);
settings["client_postCodeRef_Service"].Value = textBox1.Text; <- line 59
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("applicationSettings");
Console.WriteLine("nothing 2 " + ConfigurationManager.AppSettings["client_postCodeRef_Service"]);
}
catch (ConfigurationErrorsException e)
{
MessageBox.Show("[Exception error: {0}]",
e.ToString());
}
}
here is the config file
<applicationSettings >
<Client.Properties.Settings>
<setting name="client_postCodeRef_Service" serializeAs="String">
<value>http://127.0.0.1/directory/directory/webService.asmx</value>
</setting>
</Client.Properties.Settings>
</applicationSettings>

You are using applicationSettings not appSettings.
The two are different sections of you config file.
To use an entry in the applicationSettings you use this syntax:
string result = Client.Properties.Settings.Default.client_postCodeRef_Service;
also note that you can't easily change the value of an applicationSetting entry from inside your program.
A detailed discussion on the pros and cons of applicationSettings and AppSettings can be found here

Related

How can I change the value of a custom configSections variable?

I have a custom section in the configSections of my App.config file, how can I change the value of one of the variables of this section in code?
The section I would like to change is "serverConfiguration", and I want to change the value of "serverUrl":
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="serverConfiguration" type="someType" />
</configSections>
<serverConfiguration serverUrl="http://development/server/" />
</configuration>
I found this piece of code below from this previous question, App.Config change value.
It looks close to what I need, but I am not sure how to change it myself to use it for a custom section rather than the AppSettings. Will the code below work for what I am trying to do? How do I change the code below to allow me to pass this new String as serverUrl "http://staging/server/"? Thanks!
class Program
{
static void Main(string[] args)
{
UpdateSetting("lang", "Russian");
}
private static void UpdateSetting(string key, string value)
{
Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
configuration.AppSettings.Settings[key].Value = value;
configuration.Save();
ConfigurationManager.RefreshSection("appSettings");
}
}
You have an option to load the config into XML, edit the node value and save it back. Give a try with this
var xmlDoc = new XmlDocument();
xmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
xmlDoc.SelectSingleNode("//serverConfiguration").Attributes["serverUrl"].Value = "http://staging/server/";
xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
Probably, it is a good idea to refresh the Config sections after file is saved.
ConfigurationManager.RefreshSection

C# How do I modify configuration file of another application and save the change?

I know similar question was asked before more than once. I read some of the answers yet didn't find a clear one for my issue. To the point, I two applications say A & B. App A has a configuration file as follows:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key = "Key0" value = "4567" />
<add key = "Key1" value = "1" />
<add key = "Key2" value = "2" />
</appSettings>
</configuration>
App B tries to modify "Key0" of App A configuration file:
namespace ModifyOtherConfig
{
public partial class Form1 : Form
{
string otherConfigFilePath;
public Form1()
{
InitializeComponent();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void button1_Click(object sender, EventArgs e)
{
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = #"c:\users\om606\documents\visual studio 2015\projects\csharptesting\csharptesting\bin\debug\csharptesting.exe";
Configuration otherConfig = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
string otherSetting = otherConfig.AppSettings.Settings["Key0"].Value;
MessageBox.Show(otherSetting);
otherSetting = "098";
MessageBox.Show(otherSetting);
otherConfig.SaveAs(fileMap.ExeConfigFilename, ConfigurationSaveMode.Full);
}
}
}
When I try to run this code I get the following error:
An unhandled exception of type 'System.Configuration.ConfigurationErrorsException' occurred in System.Configuration.dll
Additional information: Data at the root level is invalid. Line 1, position 1.
What do I do wrong? Do I miss something very obvious? I'd appreciate if someone could point me in the right direction.
Oh, you're pointing your fileMap.ExeConfigFilename to the .exe, change it to point to the .config file instead. That's why you are seeing the xml error.
fileMap.ExeConfigFilename = #"c:\users\om606\documents\visual studio 2015\projects\csharptesting\csharptesting\bin\debug\csharptesting.exe.config";
for your other issue, do:
otherConfig.AppSettings.Settings.Remove("Key0");
otherConfig.AppSettings.Settings.Add("Key0", "098");
then save it.

Saving a SoundFile from a Button to App.Config

I already have the key called "Alert_Sound_File" in my App.Config that looks like this:
<setting name="Alert_Sound_File" serializeAs="String">
<value />
</setting>
This is what my button looks like:
public OpenFileDialog dialog1 = new OpenFileDialog();
private void browseSoundToolStripMenuItem_Click(object sender, EventArgs e)
{
DialogResult result = dialog1.ShowDialog();
dialog1.Title = "Browse to find sound file to play first sound";
dialog1.InitialDirectory = #"c:\";
dialog1.Filter = "Wav Files (*.wav)|*.wav";
dialog1.FilterIndex = 2;
dialog1.RestoreDirectory = true;
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
AppSettingsSection app = config.AppSettings;
app.Settings["Alert_Sound_File"].Value = dialog1.FileName;
config.Save(ConfigurationSaveMode.Modified);
}
The current error I get is:
"Object reference not set to an instance of an object."
But dialog1.FileName is set in the button, how am I getting a null value returned?
I have even tried this to test & this does not save into my App.Config:
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
AppSettingsSection app = config.AppSettings;
app.Settings.Add("y", "this is Y");
config.Save(ConfigurationSaveMode.Modified);
UPDATE: I have added
<appSettings>
<add key="Alert_Sound_File" value="" />
<add key="Error_Sound_File" value="" />
To my App.Config file and have this in my button:
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
AppSettingsSection app = config.AppSettings;
if (result == DialogResult.OK)
{
app.Settings["Alert_Sound_File"].Value = dialog1.FileName;
config.Save(ConfigurationSaveMode.Modified);
}
The result is that I do not get the Object reference error anymore but the sound file is not being added to the App.Config file. But I do not get any errors!
please try that in order to be sure that you've selected a file before:
if (result == DialogResult.OK) {
app.Settings["Alert_Sound_File"].Value = dialog1.FileName;
config.Save(ConfigurationSaveMode.Modified);
}
Change your app.config file to:
<configuration>
<appSettings>
<add key="Alert_Sound_File" value="" />
</appSettings>
</configuration>
And you need check dialog result as wrotes at previous post, because if user click cancel field is erased(maybe it really needed?).
For saving you need call save method after modified setting value:
config.Save(ConfigurationSaveMode.Modified);

Update config file

I have a problem with update my ConfigFile in VS2013 with C#.
I have this code:
Configuration configManager = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
KeyValueConfigurationCollection confCollection = configManager.AppSettings.Settings;
confCollection["ID_Uzivatele"].Value = ID_Uzivatele;
configManager.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection(configManager.AppSettings.SectionInformation.Name);
(ID_Uzivatele is a String variable)
and configFile
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="ID_Uzivatele" value="default"/>
</appSettings>
</configuration>
My problem is that(error list):
An unhandled exception of type 'System.NullReferenceException' occurred in KomunikacniAplikace.exe
Anybody has an idea what I am doing wrong?
I would suggest looking at an error case where the setting isn't set: this works for me:
(assuming theres a const for the string so you don't get a typo...)
const string ID_UZIVATELE = "ID_Uzivatele";
Main code:
Configuration configManager = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
KeyValueConfigurationCollection confCollection = configManager.AppSettings.Settings;
if (confCollection.AllKeys.Contains(ID_UZIVATELE)) {
Console.Out.WriteLine("Contains key, modifying : was " + confCollection["ID_Uzivatele"].Value);
confCollection["ID_Uzivatele"].Value = "foo";
} else {
Console.Out.WriteLine("Doesn't contain key, adding");
confCollection.Add(ID_UZIVATELE, "Boom");
}
configManager.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection(configManager.AppSettings.SectionInformation.Name);
If the config file is missing, this will generate it( you might want to check that your App.Config is actually being copied to the output folder (which might be the root cause of your error), but building protection against bad config is always helpful.

How to read AppSettings from app.config in WinForms

I usually use a text file as a config. But this time I would like to utilize app.config to associate a file name (key) with a name (value) and make the names available in combo box
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Scenario1.doc" value="Hybrid1"/>
<add key="Scenario2.doc" value="Hybrid2"/>
<add key="Scenario3.doc" value="Hybrid3"/>
</appSettings>
</configuration>
will this work? how to retrieve the data ?
Straight from the docs:
using System.Configuration;
// Get the AppSettings section.
// This function uses the AppSettings property
// to read the appSettings configuration
// section.
public static void ReadAppSettings()
{
try
{
// Get the AppSettings section.
NameValueCollection appSettings = ConfigurationManager.AppSettings;
// Get the AppSettings section elements.
Console.WriteLine();
Console.WriteLine("Using AppSettings property.");
Console.WriteLine("Application settings:");
if (appSettings.Count == 0)
{
Console.WriteLine("[ReadAppSettings: {0}]",
"AppSettings is empty Use GetSection command first.");
}
for (int i = 0; i < appSettings.Count; i++)
{
Console.WriteLine("#{0} Key: {1} Value: {2}",i, appSettings.GetKey(i), appSettings[i]);
}
}
catch (ConfigurationErrorsException e)
{
Console.WriteLine("[ReadAppSettings: {0}]", e.ToString());
}
}
So, if you want to access the setting Scenario1.doc, you would do this:
var value = ConfigurationManager.AppSettings["Scenario1.doc"];
Edit:
As Gabriel GM said in the comments, you will have to add a reference to System.Configuration.
app settings in app.config are to store application/environment specific settings not to store data which binds to UI.
If you cant avoid storing in config because of weird business requests I would rather stick to one single setting
<add key="FileDropDown" value="File1-Value|File2-Value" />
and write C# code to get this setting ConfigurationManager.AppSettings["FileDropDown"] and do some string Splits ('|') and ('-') to create kvp collection and bind it to UI.

Categories

Resources