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);
Related
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.
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.
I have a config file in my project, which I am not able to read in for some reason. Similar code has worked for me in the past. I am not sure what am I doing wrong here. I was wondering if someone would be able to have a look and let me know if I am doing something wrong. Please help...
Here's my code:
KeyValueConfigurationCollection settings;
Configuration config;
ExeConfigurationFileMap configFile = new ExeConfigurationFileMap();
configFile.ExeConfigFilename = "myProject.exe.config";
config = ConfigurationManager.OpenMappedExeConfiguration(configFile, ConfigurationUserLevel.None);
settings = config.AppSettings.Settings;
this.logFilePath = settings["logFilePath"].Value;
this.logFilePath = settings["logFileName"].Value;
Here's my Config File:
<?xml version="1.0"?/>
<configuration>
<add key="logFilePath" value=".//Results//" />
<add key="logFileName" value="Output.xml" />
</configuration>
Thanks in advance,
Harit
harit, try amending your structure to:
<?xml version="1.0"?/>
<configuration>
<appSettings>
<add key="logFilePath" value=".//Results//" />
<add key="logFileName" value="Output.xml" />
<appSettings>
</configuration>
Using the ConfigurationManager creates the requirement for this exact structure to be present. it should work as planned with the above change.
The AppSettings Collection is missing from your configuration. You only have the root-level of configured. But you are requesting in your code.
Your configuration should be
<configuration>
<appSettings>
<add key="logFilePath" value=".//Results//" />
<add key="logFileName" value="Output.xml" />
</appSettings>
</configuration>
Read values from different web.config:
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = AppDomain.CurrentDomain.BaseDirectory + #"second.config";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap,ConfigurationUserLevel.None);
ConfigurationSection mySection = config.GetSection("countoffiles");
if (config.AppSettings.Settings.Count > 0)
{
System.Configuration.KeyValueConfigurationElement customSetting =
config.AppSettings.Settings["countoffiles"];
if (customSetting != null)
{
Response.Write(customSetting.Value);
}
else
{
Console.WriteLine("No countoffiles application string");
}
}
I have the following in my App.config file
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="save" value="C:\Test"/>
</appSettings>
</configuration>
And the following in my Main.cs
private void tsSaveImage_Click(object sender, EventArgs e)
{
SaveFileDialog sd = new SaveFileDialog();
sd.Filter = "TIFF Files (*.tif)|*.tif";
sd.FilterIndex = 1;
sd.InitialDirectory =
}
I would like to know how I can use the value from the key to set the InitialDirectory. The idea being that Once the app is installed I want users to navigate to app.config file and change this just the once.
Is this a good way or are there better methods?
You can set the initail directory from web.config key by
sd .InitialDirectory = ConfigurationManager.AppSettings[key].ToString();
You need to use the ConfigurationManager:
string value = ConfigurationManager.AppSettings[key];
In your case:
value = ConfigurationManager.AppSettings["save"];
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