Specify AppSettingsReader() to look in different app.config for key - c#

I'm using the AppSettingsReader() method to get a value from a given key in the app.config file:
var value = new AppSettingsReader().GetValue("SomeKey", typeof(string)) as string;
This is done in a class which is in a seperate assembly with its own app.config file. Now if I specify the key/value pair in this app.config:
<appSettings>
<add key="SomeKey" value="MyValue" />
</appSettings>
It throws the error:
"The key 'SomeKey' does not exist in the appSettings configuration section."
Because it looks in the App.config file from my main application which is, as stated before, in a different assembly. When I put my key/value pairs in there it works properly.
Is there a way of telling AppSettingsReader() to look in the app.config of the assembly from which it is called and not in the main (parent) assembly?

For this case you can use the ConfigurationManager class. It allows you to open configuration files from various places. To open a .config file, other than the one from the .exe, you could use the method OpenMappedExeConfiguration.
string pathToOtherConfigFile = ""; //you need to specify the path
ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();
configMap.ExeConfigFilename = pathToOtherConfig;
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
var value = config.AppSettings["SomeKey"];

Related

Replacing app.config at runtime

Here is my appconfig:
<connectionStrings>
<add name ="cn" connectionString="User ID=YOUR_USER_HERE; Password=YOUR_PASS_HERE;Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=.)(PORT=1521)))(CONNECT_DATA=(SERVICE_NAME=.)));"/>
</connectionStrings>
I have tried this function:
public void updateConfigFile(string con)
{
//updating config file
XmlDocument XmlDoc = new XmlDocument();
//Loading the Config file
XmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
foreach (XmlElement xElement in XmlDoc.DocumentElement)
{
if (xElement.Name == "connectionStrings")
{
{
xElement.FirstChild.Attributes[1].Value = con;
}
}
}
//writing the connection string in config file
XmlDoc.Save("App.config");
}
That did not work. It ran without any error. But it did not save connectionString into appconfig file. I also tried this idea:
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
connectionStringsSection.ConnectionStrings["Blah"].ConnectionString = "Data Source=blah;Initial Catalog=blah;UID=blah;password=blah";
config.Save();
ConfigurationManager.RefreshSection("connectionStrings");
I get an error that says UnauthorizedAccess. ( I believe it is because of my school network)
These two options have not worked so far. I also tried to set ConfigurationManager.ConnectionStrings["cn"] to my custom connectionString. Since it is readonly, that failed too. Is there any other idea that I can replace connectionString at runtime?
Thanks in advance.
Changing the app configuration file must be done before your application starts, as certain keys are read by the runtime when your application is being bootstrapped only, and others are turned into readonly.
You can dynamically change the configuration entries of the AppSettings section only by referencing the System.Configuration assembly. All the other keys are by design read only.
If you don't want to alter the configuration before starting the application, you need to think about all the involved entities: who is going to read your connection string? If it is you, you can simply store it somewhere else or even in the AppSettings key. Instead, if external components require to read it from your configuration file, you have no chance that changing the architecture of your application in order to have a wrapper that does the changes before running your application.
The AppSettings key ca be changed in this way, after refencing the System.Configuration assembly (this is vital).
App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="key1" value="configuration"/>
</appSettings>
</configuration>
Program.cs
using System;
using System.Configuration;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
System.Configuration.ConfigurationManager.AppSettings["key1"] = "changed";
var value = System.Configuration.ConfigurationManager.AppSettings["key1"];
Console.WriteLine($"This is the new key: {value}.");
}
}
}

Modifying appSettings "file" attribute at runtime

string appConfPath = Directory.GetParent(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)).FullName;
string fullPath = appConfPath + "\\Local\\RandFolder\\ThisOne\\application.settings.xml";
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.File = fullPath;
config.AppSettings.Settings.Add("Password", "djydyjdjtdtyjddj");
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
var temp = config.AppSettings;
I am currently trying to set the "file" attribute of my appSettings configuration and reference XML's included settings at runtime. I am unable to do this before compile because the XML settings file will change based on the local machines settings.
However, after making the above changes, the temp variable only contains the "Password" item and is unable to retrieve the other settings located in the included file path. I know the file attribute is being set but for some reason the referenced setting are still hidden. The application.settings.xml file looks like this...
<?xml version="1.0" encoding="utf-8"?>
<appSettings>
<add key="ServerLocation" />
<add key="PerforceURI" value="yuhsgbyluvgblsg" />
</appSettings>
Any help is greatly appreciated!
I won't try to critique what you are doing, but provide you with a simple explanation of what you are seeing.
ConfigurationManager.RefreshSection refreshes the section in the Configuration instance used by the static ConfigurationManager. It does not effect the Configuration instance you created by calling OpenExeConfiguration; for that to occur you would need to call OpenExeConfiguration again.

How to modify custom sections of the web.config file, from a generic .NET application?

I have a WinForm derived application (note NOT an ASP.NET web application) from where I need to modify a custom section of an arbitrary web.config file. As an example, if my web.config is something like this:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!-- General web.config stuff follows -->
<system.web>
<httpRuntime executionTimeout="110" maxRequestLength="1024" requestValidationMode="2.0" />
</system.web>
<MyConfigSection>
<GeneralParameters>
<param key="Var1" value="value1" />
</GeneralParameters>
</MyConfigSection>
</configuration>
I can easily modify some default parameter, say, for maxRequestLength I'd do this and it would work:
//Path to the web.config file
string strWebConfigFile = #"C:\My files\web.config";
//Convert absolute path to virtual
var configFile = new FileInfo(strWebConfigFile);
var vdm = new VirtualDirectoryMapping(configFile.DirectoryName, true, configFile.Name);
var wcfm = new WebConfigurationFileMap();
wcfm.VirtualDirectories.Add("/", vdm);
//Open web.config file
System.Configuration.Configuration config =
System.Web.Configuration.WebConfigurationManager.OpenMappedWebConfiguration(wcfm, "/");
if (config != null)
{
System.Configuration.ConfigurationSection system_web =
config.GetSection("system.web/httpRuntime");
PropertyInformation pi = system_web.ElementInformation.Properties["maxRequestLength"];
pi.Value = 1234; //Set new value
//Save
config.Save(ConfigurationSaveMode.Modified);
}
The issue is when I try to modify my custom section. Say, if I wanted to rewrite Var1 parameter's value with value2, the following:
System.Configuration.ConfigurationSection genParams = config.GetSection("MyConfigSection/GeneralParameters");
returns null and if I call it with just MyConfigSection, it gives me this exception:
An error occurred creating the configuration section handler for
MyConfigSection: Could not load type 'MyWebApp.Configuration' from
assembly 'System.Web, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=N'.
What shall I do here to add that "configuration section handler"?
You have to open it up with XmlDocument, and work with it, sorry. That is how we cracked this nut - sorry I'm not at liberty to give you the code.

Using ConfigurationManager's OpenExeConfiguration and GetSection,(Custom config file and section)

Is it possible to retrieve a custom configuration section from a config file other than the app.config or web.config.
I tried using the System.Configuration.ConfigurationManager's OpenExeConfiguration and GetSection method calls together but without luck. My intention is to define custom configuration sections for interchangeable process adapters and contain the custom config section in a separate config file other than app.config and web.config. I see plenty of examples for appsettings and connectionstrings.
static private DigiKeyReadTaskConfigSection digiKeyReadTaskConfigSection;
static DigiKeyReadTaskConfigSection DigiKeyReadTaskConfigSection {
get {
if (digiKeyReadTaskConfigSection == null) {
digiKeyReadTaskConfigSection = (DigiKeyReadTaskConfigSection)ConfigurationManager.OpenExeConfiguration("ReadTask.config").GetSection("DigiKeyReadTaskConfigSection");
}
return digiKeyReadTaskConfigSection;
}
}
The digiKeyReadTaskConfigSection = (DigiKeyReadTaskConfigSection)ConfigurationManager.OpenExeConfiguration call seems to be working however the (DigiKeyReadTaskConfigSection)ConfigurationManager.OpenExeConfiguration("ReadTask.config").GetSection("DigiKeyReadTaskConfigSection") returns null.
The ReadTask.config file lives in the bin file of the App:
<configuration> <configSections>
<section name="DigiKeyReadTaskConfigSection" type="DataReadInc.WebSiteRead.TaskConfigSection.DigiKeyReadTaskConfigSection, DataReadInc.WebSiteRead" />
<section name="ArrowReadTaskConfigSection" type="DataReadInc.WebSiteRead.TaskConfigSection.ArrowReadTaskConfigSection, DataReadInc.WebSiteRead" /> </configSections> <DigiKeyReadTaskConfigSection DigiKeySiteURL="http://search.digikey.com/scripts/DkSearch/dksus.dll?WT.z_header=search_go&lang=en&site=us&keywords="
SiteLogInURL="https://ordering.digikey.com/RegisteredUser/Login.aspx,formName=" SiteLoginId="X" SiteLoginPassword="X" /> <ArrowReadTaskConfigSection ArrowAmericaSiteURL="http://components.arrow.com/part/search/"
SiteLoginURL="http://components.arrow.com/login/processlogin#" SiteLoginId="X" SiteLoginPassword="X" /> </configuration>
I have seen this type of setup with Spring.Net and a J2EE implementation so I am sure it is possible. I can just put my custom config sections in the App.config or web.config file, however it would be significantly cleaner for them to exist in their own config file.
Use ConfigurationManager.OpenMappedExeConfiguration(). OpenExeConfiguration relates to a certain exe.

How to open a config file app settings using ConfigurationManager?

My config file is located here:
"~/Admin/Web.config"
I tried opening it via the below code but it didn't work:
var physicalFilePath = HttpContext.Current.Server.MapPath("~/Admin/Web.config");
var configMap = new ConfigurationFileMap(physicalFilePath);
var configuration = ConfigurationManager.OpenMappedMachineConfiguration(configMap);
var appSettingsSection = (AppSettingsSection)configuration.GetSection("appSettings");
when appsettings line runs, it throws the below error message:
Unable to cast object of type 'System.Configuration.DefaultSection' to type 'System.Configuration.AppSettingsSection'.
My Web.Config looks like below:
<?xml version="1.0"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
<appSettings>
<add key="AdminUsername" value="Test1"/>
<add key="AdminPassword" value="Test2"/>
</appSettings>
<connectionStrings></connectionStrings>
</configuration>
How could I get the appsettings?
For web-app, you need to use System.Web.Configuration.WebConfigurationManager class and no need to set absolute path.
var web=System.Web.Configuration.WebConfigurationManager
.OpenWebConfiguration("~/admin/web.config");
String appValue=web.AppSettings.Settings["key"].Value;
If you are looking for adding some stuff to the Web.config, and then reading it from the code.
What you need is Custom Configuration Sections in Web.config
Look here:
How do I define custom web.config sections with potential child elements and attributes for the properties?
and here:
Creating Custom Configuration Sections in Web.config - 4GuysFromRolla.com

Categories

Resources