Custom InitialDirectory C# using app.config - c#

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

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.

C# ConfigurationManager not returning value

I'm trying to get a value from my configuration file
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="MusicPath" value="C:/Users/Alvaro/Music" />
</appSettings>
</configuration>
And this is how I handle it
this.config = new ConfigurationHandler();
String musicPath = this.config.MusicPath();
DirectoryInfo dinfo = new DirectoryInfo(musicPath);
And this is the ConfigurationHandler class
namespace RaggaerPlayer.Class
{
class ConfigurationHandler
{
public String MusicPath()
{
String path = ConfigurationManager.AppSettings["MusicPath"];
return path;
}
}
}
But I got an error at the DirectoryInfo variable "Value cannot be null".. what am I doing wrong?
I believe the file should be named App.config. You could rename it, but I think this causes versioning problems.

Categories

Resources