Can not read Config File - c#

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

Related

C# App.Config File Path combine

I'm trying without success to use app.config keys with file path based.
This is my App.Config:
<appSettings>
<add key="States" value="NY,CA,MA" />
<add key="SourceFile_NY" value="C:\NY\file.xlsx" />
<add key="SourceFile_CA" value="C:\CA\file.xlsx" />
<add key="SourceFile_MA" value="C:\MA\file.xlsx" />
Now, on the main class, i'd like to obtain the file for each state given:
static void Main(string[] args)
{
var states = "NY,CA,MA".Split(',');
foreach (var state in states)
{
new SomeMethodFromOtherClass().class(SourceFile_ + XX);
}
}
I'm trying to get the file path based on the state on the SourceFile_ + XX part, but i can't find any good way to accomplish the call to the app.config value for each state
Make sure you add a reference in your project to System.Configuration.
Then you just do:
var ny = ConfigurationManager.AppSettings[sourcefile + "_NY"];

How to create a custom app.config with just one extra entry

I want my app.config file to be something like
<configSections>
<section name ="RegCompany" type =""/>
</configSections>
<RegCompany>
<Company name="Tata Motors" code="Tata"/>
<SomethingElse url="someuri"/>
</RegCompany>
Any idea how to do this? I want to get the values defined here through my code.
For simple values like this, there is an easier solution than the one in the duplicate questions.
Config:
<configSections>
<section name="RegCompany" type="System.Configuration.NameValueSectionHandler"/>
</configSections>
<RegCompany>
<add key="CompanyName" value="Tata Motors" />
<add key="CompanyCode" value="Tata" />
<add key="CompanyUrl" value="example.com" />
</RegCompany>
Code:
var section = ConfigurationManager.GetSection("RegCompany") as NameValueCollection;
if (section == null) {
throw new InvalidOperationException("Unknown company");
}
var company = section["CompanyName"];
var code = section["CompanyCode"];
var url = section["CompanyUrl"];

Configuration.SaveAs writes empty config

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.

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.

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