Common app.config for multiple applications - c#

I have several C# console applications, which need to have the same set of settings. I want to avoid duplicity and avoid separate app.config for each application.
Is there any way to read a common app.config file (say common.config) for applications (app1.exe, app2.exe).

Create one file called app.config. Put it in some place outside of your projects' directories, like up in the solution directory. Add it to your projects as a linked item with a relative path to the file. Set the right build action for this item (application configuration) in each project.
Now when each project builds, the file will be copied to the project's output dir with the right name.

You can load an external app.config using the code below:
config = ConfigurationManager.OpenExeConfiguration(Path.Combine("C:\test\root", "Master.exe"));
string logpath = config.AppSettings.Settings["Log.Path"].Value;
And save settings as so:
config = ConfigurationManager.OpenExeConfiguration(Path.Combine("C:\test\root", "Master.exe"));
config.AppSettings.Settings["Log.Path"].Value = "C:\newpath";
config.Save();
You might have to have a master config within one of the applications and point the rest to this. Typically this method is considered bad practice though. There might be issues with different applications locking the file.

#Ran's answer is an option, but each application will still have its own config file after you build. At compile time they will be the same, but at deploy time they are copies.
You can also open one application's config file from another application using:
ConfigurationManager.OpenExeConfiguration(string)
You can have an external config file that all applications reference using:
ConfigurationManager.OpenMappedExeConfiguration
And there's the option to using the Machine config file using:
ConfigurationManager.OpenMachineConfiguration()

Related

Merging XML Config File w/ .exe

I've developed a program that utilizes Settings within my C# program. When I build the program, a separate XML Config file is created, that contains the settings of the program.
I've been able to merge other files, like the .dll's and manifest file I use for the program, into the executable. I've tried the suggested solution of putting it as a resource, but I get an error saying that it can't find the file. Secondly, the user of the program can change the settings, and I think that the Settings being implemented within the Resources isn't the best way to go. I've also set the Build Action to Embedded Resource and it still creates a separate XML Config file. How could I also merge the XML Config file with the executable?
Encrypting sections of the config file is pretty easy. There are a couple providers. The simple code for this can be seen here. I usually use it to encrypt connection strings.
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var section = config.GetSection("connectionStrings");
section.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider");
config.Save(ConfigurationSaveMode.Full);
Note: this code only takes effect at runtime. Every build will remove the encryption and once you release it and run it as expected (outside the debugger) it will encrypt it.
Link to MSN page

C# DLL config file not present

Well, this question is a bit different from others with the slightly same title.
I add a config file to my DLL which will be used from a website and a console application.
I'm testing the DLL from my web application.
When I build the DLL I can see my MyApp.dll.config in the bin\debug folder.
Nevertheless, when I try to read the settings from the DLL this way:
var appConfig = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
The file is not found.
I know it is something to do with the location where the application is being executed as Assembly.GetExecutingAssembly().Location return a path in Framework\v4.0.30319\Temporary ASP.NET Files\root\... while AppDomain.CurrentDomain.BaseDirectory return another completely different path.
So, what I'm doing wrong? There is some configuration missing to get the config file to be copied in the real location where the application is being ran?
Thank you in advance from your help!
Usually when you build a .dll and it has a config, that file lives with the dll in the same folder.
Alas, when you use your dll in another project, that project usually has it's own config, which takes precedence over the dll's one.
You could either add the dll's config to the parent's config, or try configuring what you need in code, instead of in the config.
In .NET DLLs can not have configuration files. They will simply not be used. They are created if you use the settings tab in the project properties, but they will not be read. What you need to do is merge the settings from that config file into the application's configuration (in your case, the web.config file).

Copy settings from one Web.config to another except AppSettings and ConnectionStrings

Is it possible, through code, to copy settings from one Web.config file to another (except AppSettings and ConnectionStrings)?
I have a situation where a single MVC3 project has been deployed to multiple servers in different locations. There is an auto-updater on all of these that will pull in the latest version. Typically when this would run, it would only overwrite the application folders and NOT the Web.config file.
I just upgraded the project to MVC4. This changes basically everything in the Web.config file except the AppSettings and ConnectionStrings. All of the installations of this project would have slightly different values here.
How would I go about writing some code that will update the Web.config file, but preserve all of the AppSettings and ConnectionStrings?
.NET provides ways to get configuration from other config file. Refer this article:http://blog.andreloker.de/post/2008/06/Keep-your-config-clean-with-external-config-files.aspx
Basically, you can use "configSource" attribute to define which config file to refer. Note that the configuration file should be in same directory. if not, Refer here to solve the problem. .NET Config Files configSource outside the application directory folder

How to handle two or more app configs?

Lets imagine I have three projects in my solution. The first one is executeble and the other two are class libraries.
Every project has it's own app.config file which contain some httpBinding data, some user settings and connection strings.
Then I build the solution and all I get (in the EXE's bin directory) is the only app.config file with the XML elements wich are related to the executable project.
So, the question. How do I suppose to use that another two configs (which are successefully built to their corresponding project bin folders?
You need to put the settings in the dll libraries in the setting file of executable. Or you can make a separate libraries for handling settings of all the projects in the solution. The default setting files look in to app.config.

Can a Console Application reference its .exe.config if the .config is in another folder?

Here is the task I have been given at work. We have a Web Application for which I created a Console Application that can be executed by the Scheduled Tasks on a daily basis. The task I have be presented with is to discover if we can place the ConApp.exe and the ConApp.exe.config in two different directories (folders) in our application. We would like to place the .exe file in the bin folder with all the .dll's and place the .exe.config file in a central configurations folder. I have been looking around in the properties and such with in Visual Studio and I do not see any options that will allow me to specify to the ConApp.exe the location of the ConApp.exe.config.
Is there a way to place these two files in separate folders or do they need to be in the same folder and have the .exe.confing reference a central .config file?
Thanks, :)
You should be able to use ConfigurationManager.OpenExeConfiguration to do that. You can add a setting in the console application's config file that points out the path and filename to the config file, and pass that value to OpenExeConfiguration (granted that the console runs as an account that has read access to the location where the config file is stored).
Note that if your console app contains statements like ConfigurationManager.AppSettings["somekey"], these will need some rewriting so that they use the Configuration object returned by the OpenExeConfiguration method.
The automatic discovery of the .exe.config works only if the files are in the same folder. But you gave the answer yourself IMHO: have the .exe.config reference another .config file in the desired central location.
No, you cannot tell your app to look in another directory for its main app.config.
What you can do is externalize certain configuration sections to external files in another directory:
<configuration>
<appSettings configSource="config\appSettings.config" />
<connectionStrings configSource="config\connections.config" />
</configuration>
This works - even though in the Visual Studio designer there will be complaints about this - on any .NET configuration section (but not on section groups, e.g. you cannot externalize the entire <system.web> or <system.serviceModel> at once - you need to do it by their sub-elements.
So with help from Fredrik Mork I was able to figure out this solution. First of all when you create your Console Applications, DO NOT, create any setting in the projects properties window. This will create an app.config file in your project which I believe the executable will try to look for and crash if it doesn't find it. When you first create the Console Application and then Build it before writing any code. Visual Studio create the Debug folder with just the executable file and a few supporting files. I then placed this code in the "main" function:
Dim fileMap As ExeConfigurationFileMap = New ExeConfigurationFileMap()
fileMap.ExeConfigFilename = "....../AppName.config"
Dim externalConfig As Configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None)
Dim appS As AppSettingsSection = externalConfig.Sections("appSettings")
Dim reportURL As String = appS.Settings("URL").Value
Console.Writeline(reportURL)
In the 2nd line "fileMap.ExeConfigFilename = "....../AppName.exe.config" then "......" represent the full pathname to the config file and AppName is the name of your file. Now I also tried to copy the code from my original Console Application and run it but it still crashed. I think it is due to the .dlls that I am using which make calls to Stored Procedures on the database. I believe these dlls are looking for the .config file to be in the same folder since that is the way they were built. However, if you are careful when you begin writing your application you can utilize Web.config information like I did above.

Categories