Configuration.SaveAs writes empty config - c#

Getting some odd behavior from Configuration class. This code
class Program
{
static void Main(string[] args)
{
var configFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
var configuration = ConfigurationManager.OpenExeConfiguration(configFile);
var value = configuration.AppSettings.Settings["Supercali"];
if (value != null) Console.WriteLine("Yay, it finally worked!");
else Console.WriteLine("Still broken.");
configuration.SaveAs("ReadConfig.config");
}
}
with this config in AppDomain.CurrentDomain.SetupInformation.ConfigurationFile:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<appSettings>
<add key="Supercali" value="Fragalistic"/>
</appSettings>
</configuration>
writes the following to "ReadConfig.config"
<?xml version="1.0" encoding="utf-8"?>
<configuration>
</configuration>
and prints this
Still broken.
Looking at it in debug view, AppDomain.CurrentDomain.SetupInformation.ConfigurationFile has the correct file, but OpenExeConfiguration seems to create a blank config. The appSettings section is empty. I'm pretty sure this is wrong, but maybe I'm missing something?

Try this:
var configFile = Assembly.GetExecutingAssembly().Location;
var configuration = ConfigurationManager.OpenExeConfiguration(configFile);
var value = configuration.AppSettings.Settings["Supercali"];
if (value != null) Console.WriteLine("Yay, it finally worked!");
else Console.WriteLine("Still broken.");
configuration.SaveAs("ReadConfig.config");
The OpenExeConfiguration expects the path to a DLL/EXE, not to the .config file.

Related

I cant get the results

I'm using this code to get the values from app.config but I get an error. I tried another little application and it turns right.
What am I doing wrong?
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i < 61; i++ )
{
this.comboBox1.Items.Add(i.ToString("D2"));
this.comboBox2.Items.Add(i.ToString("D2"));
}
string minutos = ConfigurationManager.AppSettings["minutos"];
string segundos = ConfigurationManager.AppSettings["segundos"];
//label3.Text = minutos;
this.comboBox1.SelectedIndex = 30;
this.comboBox2.SelectedIndex = 59;
}
This is the error
https://ibb.co/LSCPsxN "tooltip"
It appears (from this link hidden in the comments) that you've added your settings directly to the <configuration> node, rather than inside an <appSettings> node.
Try modifying your config by adding an appSettings node and then placing your settings inside it, like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1"/>
</startup>
<appSettings>
<add key="minutos" value="30"/>
<add key="segundos" value="59"/>
</appSettings>
</configuration>

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.

Can not read Config File

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

Write to just one XML attribute without affecting the rest

I have the following but its not working for me:
static void SaveVersion(string configFile, string Version)
{
XmlDocument config = new XmlDocument();
config.Load(configFile);
XmlNode appSettings = config.SelectSingleNode("configuration/appSettings");
XmlNodeList appKids = appSettings.ChildNodes;
foreach (XmlNode setting in appKids)
{
if (setting.Attributes["key"].Value == "AgentVersion")
setting.Attributes["value"].Value = Version;
}
config.Save(configFile);
}
The config file i'm loading up on config.Load(configFile) is the following:
<?xml version="1.0"?>
<configuration>
<startup>
<supportedRuntime version="v2.0.50727" />
</startup>
<appSettings>
<add key="AgentVersion" value="2.0.5" />
<add key="ServerHostName" value="" />
<add key="ServerIpAddress" value="127.0.0.1" />
<add key="ServerPort" value="9001" />
</appSettings>
</configuration>
Am I missing something? I figured it would edit just that particular attribute AgentVersion but its not really doing anything.
Are you aware of the ConfigurationManager class? You can use it to manipulate your app.config file without doing anything manually. I don't think you should reinvent the wheel unless you have a good reason to:
static void SaveVersion(string configFile, string version)
{
var myConfig = ConfigurationManager.OpenExeConfiguration(configFile);
myConfig.AppSettings.Settings["AgentVersion"].Value = version;
myConfig.Save();
}
Try this:
static void SaveVersion(string configFile, string Version)
{
var config = new XmlDocument();
config.Load(configFile);
var agentVersionElement = config.DocumentElement.SelectSingleNode("configuration/appSettings/add[#key = 'AgentVersion']") as XmlElement;
if (agentVersionElement != null)
agentVersionElement.SetAttribute("value", version);
config.Save(configFile);
}
Note that I'm doing the SelectSingleNode from the DocumentElement, not from the XmlDocument itself.

Categories

Resources