ConfigurationManager.AppSettings use another config file - c#

I have about 10 methods in my class. In every method I use ConfigurationManager.AppSettings to get value form App.config file
like
_applicationPort = int.Parse(ConfigurationManager.AppSettings["ApplicationPort"]
My problem is that I want to make this code get AppSettings from another app.config file like AnotherPoject.exe.config.

You can also set the app.config to read another file. Something like this:
<?xml version="1.0"?>
<configuration>
<appSettings file="my\custom\file\path\external.config"/>
</configuration>
and the external.config will have the appSettings section:
<appSettings>
<add key="myKey" value="myValue" />
</appSettings>
refer to this msdn for additional info.

You could do something like this
var fileConfig = ConfigurationManager.OpenExeConfiguration("<filePath>");
int port = int.Parse(fileConfig.AppSettings["PortNumber"].ToString());

You can accomplish this by using ConfigurationManager.OpenExeConfiguration. This will allow you to open another configuration file easily.
MSDN article about OpenExeConfiguration.

Related

C# Cannot read from App.config file in MVC

I have an MVC project and am trying to store my API keys in a separate config file which I will ignore when pushing the code to Git. According to MSDN I should be able to store them in an App.config like like so
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="APIKey" value="APIKeyValue" />
</appSettings>
</configuration>
I should then be able to read from the file by creating a method in a model
public class KeyTest
{
public string KeyTestCall()
{
string testkey = ConfigurationManager.AppSettings.Get("APIKey");
return testkey;
}
}
and then invoke the method in my controller to assign the value from my App.config file (just so I know I'm getting the value).
public void Testing()
{
KeyTest k = new KeyTest();
ViewBag.x = k;
}
At no point will the code break for a breakpoint, the build will succeed and I can't tell if I'm getting the value or not. Any help is much appreciated. Thanks!
For a web application such as an MVC app, it's a Web.config file, not an App.config
In addition to above (re: web.config vs app.config) if you want to remove "secrets" from source control, this is one way to do it:
In web.config
<?xml version="1.0" encoding="utf-8"?>
<cofiguration>
....
<appSettings file="AppKeys.config">
<add key="SomeOtherSettingThatHasNoSecrets" value="foo" />
...
Then in a separte AppKeys.config file (you can name this whatever.config, sample as named in the above), that you don't add to Git/source control:
<appSettings>
<add key="SomeSecretKey" value="the secret" />
...
Note that AppKeys.config doesn't have an XML declaration.
Hth.

Adding and reading a custom section in AppSettings in C#

I hope you can help me.
I'm supposed to add a new type of values to an AppSettings file (already existing with some values). Those values are a whole list of special folders so I thought the best way would be to have a new section for those folder values so that the file would look like this:for
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="usPath" value="folderName1" />
<add key="tcPath" value="folderName2" />
<add key="usGUID" value="folderID1" />
<add key="tcGUID" value="folderID2" />
</appSettings>
<updateFolders>
<add key="folderID3" value="folderName3">
<add key="folderID4" value="folderName4">
</updateFolders>
</configuration>
Reading and writing within the already existing appSettings-tag is no problem but I haven't find a way yet to modify the updateFolders section. I'm really new to using AppSettings in this way so I don't know too much about what's possible and what's not. In addition to that I think the AppSettings file might have been set up in a wrong way from the very beginning (it gets created by using a System.IO.File-Writer).
see ConfigurationManager.GetSection
http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.getsection(v=vs.110).aspx

Read AppSettings from a secondary webconfig

I created a second web config and placed it in a folder:
~/Configuration/OtherConnections.config
My config file looks like:
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="serverurl" value="http://serverUrl" />
<add key="UserName" value="myUser" />
<add key="Password" value="XXXXXXX" />
</appSettings>
</configuration>
When I attempt to read the value from one of the items like:
string connectionInfo = ConfigurationManager.AppSettings["UserName"];
I do not get a value back. Is this because the web config is in a folder, or is there something else going on in this web app?
I do not get a value back. Is this because the web config is in a folder ... ?
No, not the folder but the filename. You can use ~/Configuration/Web.config but then you have to explicity open it:
var config = WebConfigurationManager.OpenWebConfiguration("~/Configuration");
And then to read from it:
string url = config.AppSettings.Settings["serverurl"].Value;
Note that you cannot specify (and thus not change) the actual web.config file name. Just the folder.
you can have only one web.config file for each web folder
There are tow options anyway:
In the IIS Manager you need to configure the sub folder as a new application. It uses the web.config file from the running app.
Another option is using a single config file and adding a <location> section to segment the file to act differently for some folders or files. (which I would suggest more info here)
You can access multiple config files by using WebConfigurationmanager method. add namespace:
using System.Web.Configuration;
So, to access the appSettings of
../SomeProjectFolder/Environment/Web.config, you can do:
var config = WebConfigurationManager.OpenWebConfiguration("~/SomeProjectFolder/Environment/");
string username = config.AppSettings.Settings["username"].Value;
Hope this helps.

How can I access web.config from an ASP.NET Custom Control?

Inside my web.config file I've got code like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
...
<section name="UninstallSurveySettings" type="dashboard.UninstallSurveyConfig" />
</configSections>
...
<UninstallSurveySettings>
<add key="fileLocation" value="C:\inetpub\wwwroot\output\" />
</UninstallSurveySettings>
...
</configuration>
I need to be able to access this field from my custom control. The control can be dropped into any website and needs to check that site's web.config for the fileLocation value in UninstallSurveySetting.
I've tried a couple different approaches with no luck. Any help on this would be greatly appreciated.
Much easier to use AppSettings.
Web.config:
<configuration>
<appSettings>
<add key="fileLocation" value="C:\inetpub\wwwroot\output\" />
</appSettings>
</configuration>
Code:
string location = System.Configuration.ConfigurationManager.AppSettings["fileLocation"];
If your section will become more complex, then:
var section = (NameValueFileSectionHandler)ConfigurationManager.GetSection("UninstallSurveySettings");
if (section != null)
{
// access section members
}
P.S.
Maybe you want to use ConfigurationSection class instead of handler.
In ASP.NET MVC 3 the tag cannot be a direct child of (it results in a configuration error).
How about adding your key to the section. Then you can easily access it via the ConfigurationManager.AppSettings collection.
using System.Configuration.ConfigurationManager and you will be able to get what you want from the web.config
I was able to solve this by creating a configuration class for it and placing this code in the web.config:
<section name="UninstallSurveyConfig" type="dashboard.UninstallSurveyConfig" />
..
<UninstallSurveyConfig dirFileLocation="C:\inetpub\wwwroot\build\output" webFileLocation="~/output" />

Override config settings

I have a config file that is used in several projects, general.config, looks like:
<?xml version="1.0" encoding="utf-8" ?>
<appSettings>
<add key="mykey1" value="myvalue1"/>
<add key="mykey2" value="myvalue2"/>
</appSettings>
In one of the projects, I need to override one of the two settings. So the app.config of this project looks like:
<?xml version="1.0"?>
<configuration>
<appSettings file="general.config">
<remove key="mykey1"/>
<add key="mykey1" value="anothervalue"/>
<add key="mykey3" value="myvalue3"/>
</appSettings>
</configuration>
But remove is not working here. How can I override mykey1 without breaking mykey2? add works in this case. I can get myvalue3 from ConfigurationManager.
EDIT: general.config is copied to output folder automatically when compiling. Don't worry about the path issue. Currently I got:
ConfigurationManager.AppSettings["mykey1"]
//I got "myvalue1", but I want "anothervalue" here
//that is, this item is "overrided", just like virtual methods in C#
ConfigurationManager.AppSettings["mykey2"]
//this setting will not be modified, currently it works fine
ConfigurationManager.AppSettings["mykey3"] //good
A friend of mine answered this question. From MSDN:
You can use the file attribute to
specify a configuration file that
provides additional settings or
overrides the settings that are
specified in the appSettings element.
You can use the file attribute in
source control team development
scenarios, such as when a user wants
to override the project settings that
are specified in an application
configuration file. Configuration
files that are specified in a file
attribute must have the appSettings
element rather than configuration
element as the root node.
So in this question, the settings in general.config overrides items in app.config, different from that I think(want) app.config items overrides items in general.config. Now I think I have to resolve this issue in C# code(it will inevitable looks ugly).
Your use of the file attribute to load common settings with an expectation that keys added directly to the <appSettings> element would override those common settings is understandable, but unfortunately that is not how it works.
Microsoft's intention was for the file attribute to load common settings that override the individual application's settings.
This is discussed in some detail in the Microsoft Documentation
To overcome this problem, we very occasionally declare base settings in the common file, and then appropriately named overrides in the application configuration. However this does require additional code which is a bit ugly. e.g.
var config = ConfigurationManager.AppSettings["MSG_QUEUE_PROVIDER_OVERRIDE"]
?? ConfigurationManager.AppSettings["MSG_QUEUE_PROVIDER"]
?? "ActiveMQ";
<appSettings file="common.config">
<!-- Override the common values -->
<add key="MSG_QUEUE_PROVIDER_OVERRIDE" value="RabbitMQ"/>
</appSettings>
The elements are changed from the child and what i mean by that is currently your app.config is the parent file and the values are replaced by the ones existing in General.config
Since you are using remove in the parent file what its effectively doing is removing the element you specify in app.config but after that the elements from general.config are pushed in. Now say here in General.config you say remove mykey3 which is on your app.config you will see that the final collection has no key as mykey3.
In short this is not going to work. Hope this helped you.
You can add another config file say Test.config.
<appSettings>
<add key="mykey1" value="New value"/>
</appSettings>
and in the app.config appsettings section will look like this
<appSettings file="Test.config">
<add key="mykey1" value="myvalue1"/>
</appSettings>

Categories