How to specify a config file with path? - c#

I would like to setup one web.config file for my solution. How do I specify the path of the config file I am using?

Here is how you can specify new app setting in your web.config file.
<appSettings>
<add key="LoggingDir" value="C:\\Logs\\"/>
<add key="environment" value="test"/>
<add key="smtp.server" value="incoming.ABank.com"/>
</appSettings>
And you can access in your code by
private static String logDirectory = ConfigurationManager.AppSettings["LoggingDir"].ToString();
private static String MailServer= ConfigurationManager.AppSettings["smtp.server"].ToString();
I prefer all my app or environmental settings in a separate file when I have lot of them. You can do that by
<appSettings configSource="env\ApplicationSettings.config"/>
and then write above <appSettings> </appSettings> section in ApplicationSettings.config file.

If you're creating an MVC application, then generally you can access your configuration file (web.config, in the root of the project) using ConfigurationManager:
string sConnectionString = ConfigurationManager.ConnectionStrings["SqlServer"].ConnectionString;
You could try loading a different configuration file using:
ConfigurationManager.OpenExeConfiguration()
Here's a link to the MSDN documentation for the ConfigurationManager class:
http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.aspx - specifically, there's some information included there about the class's intended usage and operation.
Hope that helps,
Cheers!

Not knowing what your projets look like I'm going to go out on a limb here.
Just an FYI, in IIS there will be inheritance that may solve your issues, just be sure to setup your apps for debugging in IIS in the same folder structure.
If you have multiple libraries, you dont need config files for those libs (app.config), so what are you trying to to do eliminate multiple config files? Do you have multiple web sites? If you only have a single site and other class library projects, you won't beed other config files as they won't be used at runtime anyways. If you have multiple web sites, then consider inheritance.
10 things asp.net developers should know about web.config inheritance and overrides

Related

.NET ConfigurationSettings.AppSettings("TheDB")

I'm looking at a custom built .NET control (vb). It has a public string declared as:
Public Shared strConn As String = ConfigurationSettings.AppSettings("TheDB")
I'm trying to find out what "TheDB" is supposed to be exactly.
I looked the web.config file of the website using this custom control, but there is no "TheDB" parameter anywhere. I also looked in the web server's machine.config file, and again, no "TheDB" parameters there either.
Help.
If it's missing, just add it:
<appSettings>
<add key="TheDB" value="somevalue" />
</appSettings>
(assuming that ConfigurationSettings.AppSettings really corresponds to appSettings section of the web.config. This is not clear as normally you refer to standard sections of configuration files using builtin ConfigurationManager class)
Look in your web.config. Somewhere in there is a section called "AppSettings", where there should be some elements that look like this:
<add key="TheDB" value="something" />
One of them will be yours. Or possibly somebody took it out. More than likely, though, it's the connection string to your database.
web.config is hierarchical. Each web.config supplies configuration information to the directory in which it is located and to the entire directory hierarchy beneath it.
http://msdn.microsoft.com/en-us/library/ms178685.aspx
Been that way since .Net v1.1. When you look for a configuration value or section, the .Net configuration system looks in the lowest level web.config. If the desired value is not found, it runs up the directory tree until it finds it.
You need to run up the directory hierarchy (and yes, that includes virtual directories mounted in IIS as well) until you find the web.config file containing the desired appsetting value. There is also the IIS ApplicationHost.config as well, located at
%windir%\system32\inetsrv\config

How can I make a DLL ApplicationSettings class which reads from library.dll.config?

I'm creating a plug-in for another application as a DLL, which needs to have settings that can be configured without recompiling the DLL. I created a settings class through Visual Studio as I usually do with application projects. When I build my project a libraryname.dll.config file is created and copied to the output directly.
But, as may other people have already found and written about, this file is never used. Instead if I want to modify these DLL settings I need to merge the settings into the settings file for whatever application that is using the DLL.
The problem I have with this is the calling application is not my application, so I'd rather the configuration of my plug-in live with the rest of my files for my plug-in.
In the past I've used System.Configuration.ConfigurationManager.OpenExeConfiguration() to read a settings file for the DLL like this.
public static string GetSettingValue(string key)
{
string assemblyPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
var config = ConfigurationManager.OpenExeConfiguration(assemblyPath);
var keyVal = config.AppSettings.Settings[key]
return keyVal.Value;
}
Which would read from a settings file like this
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="URL" value="http://www.acme.com" />
<add key="EnableAdmin" value="False" />
</appSettings>
</configuration>
However, I really like newer type safe ApplicationSettings class that is created by visual studio rather then then using <appSettings> which can only store strings.
So what I'm wondering is if there is some way I could override a method or two in the ApplicationSettings class created by visual studio to get it to read from the DLL config file by default? It's not really clear to me exactly where it's being determined which config file should be read.
You can try to merge the applicationsettings file in the calling application. This SO thread explains it pretty well.
How to load a separate Application Settings file dynamically and merge with current settings?
If you do not want to mess with editing the calling application, you can just use the Configuration class like you are doing. Here's another example. I've used this approach when I needed to call a WCF service through COM.
http://www.twisted-bits.com/2012/04/use-a-net-configuration-file-with-a-class-library-dll/
Copy the applicable section to the web.config of the main site or app.config of the main executable, then ConfigurationManager.AppSettings["URL"] works just fine.

What is the best way to store/set configuration settings for a C# application?

I have some values that I want to be able to set, and the application to load them from some kind of file.
The only concept I can think of, is a simple txt file, that might have the following lines:
DatabaseName = "DB1/test"
DatabasePassword = "password"
Development = "true"
but im thinking it should be in some kind of config file? Plus reading a txt file for these values isnt exactly tidy code. It would be nice if i could get the database name by just saying in my application:
configfile.DatabaseName
Thanks,
Paul
You really should be using the built in Application Settings
You can directly access simple settings using the ConfigurationManager
ConfigurationManager.AppSettings["MySetting"] = "SomeStuff";
var mySetting = ConfigurationManager.AppSettings["MySetting"];
There is also direct access to your Connection Strings using the ConfigurationManager
var conn = ConfigurationManager.ConnectionStrings["DevSqlServer"];
All this is stored in XML files, and by default your *.config files.
To Answer Doomsknight's question from the comments
Configuration settings can be done a number of ways, but by default, they are stored in two places.
Application Level Settings are stored in a configuration file.
For executable programs this file is located in the same directory as the .exe and is named after the assembly, or executable.
Example: MyAssembly.config, Another.Assembly.config
For web applications, the settings are stored in the web.config file (usually) located in the root directory of the web application. These are applied hierarchically and one can be located at each directory level of the Web Application.
Example: MySite\web.config, MySite\SubDirectory\web.config
User Scoped Settings are stored in the user profile
Example: C:\Documents and Settings\USERNAME\Local Settings\Application Data\ApplicationName
Connection Strings are stored in the <connectionStrings></connectionStrings> section in your config file.
<connectionStrings>
<clear />
<add name="Name"
providerName="System.Data.ProviderName"
connectionString="Valid Connection String;" />
</connectionStrings>
These settings can easily be modified directly in the config file, but without writing some code to automatically refresh sections of the config file (which is possible), an application restart is typically needed.
I hope this helps out.
.NET has a configuration platform built into it. Just add an app.config file to your project and use the ConfigurationManager library to access the values.

How to read values from App.config in .Net 4.0 using configurationManager?

I am creating a windows service in .Net 4.0 and testing some functions of said service with a windows forms client by referencing the service project.
The service project has an App.config file and that file looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<clear />
<add name="myLocalMySQLDBUsername" connectionString="username"/>
</connectionStrings>
</configuration>
When a function belonging to the service calls:
ConfigurationManager.ConnectionStrings("myLocalMySQLDBUsername").ConnectionString
a null reference error is thrown because my connection string is not loaded. The only connectionStrings that are loaded are from the machine.config file located in c:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\Config\machine.config
If I create an application scope setting for the service, I can get that setting by using the My.Settings.setting -> so it's not like the App.config file is not being read.
My question is: why are my connectionStrings not being loaded from the App.config file?
Thank you for your help.
UPDATE:
Also, at this point, even a work around would be appreciated; the only reason for using app.config is to be able to encrypt the contents using the DpapiProtectedConfigurationProvider (the contents will have some username/password values for service and database connections).
I tried creating an AppSettings section manually in the app.config but those settings were also not read by the configurationManager (count = 0).
UPDATE 2:
Per a suggestion, I tried to manually open the app.config file like so:
Dim exePath As String = System.IO.Path.Combine(Environment.CurrentDirectory, "ServiceName.exe")
Dim myConfig As Configuration = ConfigurationManager.OpenExeConfiguration(exePath)
So here is the weird part, when I look inside, path is correct (points to my app.config) but the connectionStrings are still being loaded from the machine.config file (my connectionStrings are not loaded)!! ARGH
UPDATE 3:
Okay, so, I figured it out. When referencing a project(parent) from another project(child), the child's app.config is used even if the parent's classes are being used. Thus, I can get the connectionStrings to show up if I copy them over to the child's app.config. When trying to open it manually, my currentDirectory was of the child, not the parent (strange how it did not throw an exception - it wouldn't have been able to find the config file ... it just silently used the machine.config ... oh well).
Thanks all for the help!
The first thing you'll want to do is make sure that the service account has access to the file (if not running as SYSTEM). It sounds like it should be ok though since you mention My.Settings.Setting works.
The other thing to look out for is to make sure that the app.config has the name of the service executable in it - so if the service exe is MyService.exe the app.config must be named MyService.exe.config.
The last thing to make note of: libraries will read from the executable's app.config that loads the library, not the app.config that is with the library. So if you have a project for the service executable MyService and a project for the library MyServiceLibrary the code in the library will read the app.config from MyService not MyServiceLibrary.
I saw some people say this problem might be fixed by manually re-adding a reference to System.Configuration.dll
SIDE NOTE: If that really is you whole app.config file and not just a snippet then that is your problem... you're app.config file should be MUCH more complicated or .NET will not be able to load it.
WORK AROUND: Use the configuration manager to open this config file (there is an API for that.) You can't get it to load auto-magically just tell the config manager to open it.
I still think the problem is your config file is invalid -- could you please post the FULL file?
Make sure the config file is deployed to the same folder as the executable file, and that it's called your.assembly.exe.config.
I had a similar problem, but in my case it was because I had changed the project's namespace. This is also used as the application settings section element name in the config file, so the code was not finding the new section name. Fiddling with one of the custom setting's values in the project properties and rebuilding caused the new section to written into the app.config alongside the old ones which was what indicated the issue to me.

Centralised settings in C# for multiple programs

I was recently given a heap of programs to maintain and I am trying to find some help in adopting some best practices. They are essentially three independant softwares which use a common DLL to manage a series of settings the apps all share. The DLL works this way: it swaps the user settings file (XML file buried deep in the user's configurations folder in Windows), with a fix file, specified by a hardcoded (egad!) path.
The rationale behind keeping it as user settings and not app settings is that the DLL can be found in several locations (one for each app that will use it), and so the user settings file is common (if all copies of the DLL are the same compile), whereas by using application settings there would be as many app.config files as there are copies of the DLL.
I'm trying to conceive of a better way to centralise these configurations and end the senseless file swapping. One approach (actually, most likely the best approach) would be to redesign all 3 apps so they all use a central dll with its own "app.config". Are there other more recommendable venues?
Have you considered using the Windows Registry? We all hate it, but maybe it's the best option in this case as it is centralized and you could share settings easily across applications.
EDIT: If you don't like the Registry (and I don't blame you for it), you can create an XML or some other configuration file in a directory under the Application Data special folder. This is how this is done these days as far as I know.
string appData = Environment.GetFolderPath(
Environment.SpecialFolder.LocalApplicationData));
string folder = "MyApplicationName";
string fileName = "settings.xml";
string path = Path.Combine(Path.Combine(appData, folder), fileName);
For this precise problem, if it's a .Net DLL, you could use the GAC, this would centralise your DLL. All software would know where they could access this DLL. And in this way, you could have less refactoring to do.
This is only a patch for this problem only. I would not recommend this, for new developpement.
GAC in Wikipedia
You can use settings in a common file - most likely stored under AppData in the users settings folder
The advantage here is that you do not have to modify any code whatsoever.
The application would store its settings in its normal config file and refer to the common file for the dll settings:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings file="commondll.config">
<add key="KeyToOverride" value="Original" />
<add key="KeyToNotOverride" value="Standard" />
</appSettings>
</configuration>
Then in the common file commondll.config:
<appSettings>
<add key="KeyToOverride" value="Overridden" />
<add key="KeyToBeAdded" value="EntirelyNew" />
</appSettings>
Perhaps this solution that shares configuration settings between an ASP.NET app and Console app will contain useful information.

Categories