6

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).

Danny Beckett
  • 20,529
  • 24
  • 107
  • 134
Akshay J
  • 5,362
  • 13
  • 68
  • 105
  • possible duplicate of [Can multiple C# apps use one App.Config file?](http://stackoverflow.com/questions/9811414/can-multiple-c-sharp-apps-use-one-app-config-file) – Jeremy Thompson Mar 03 '13 at 03:08
  • You really shouldn't attempt to do this. A configuration file should exist in its own space unique to the application. – Security Hound Mar 03 '13 at 03:10

3 Answers3

8

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.

Ran
  • 5,989
  • 1
  • 24
  • 26
6

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.

Luke Wyatt
  • 1,126
  • 2
  • 12
  • 23
  • I haven't tried it in that fashion. You'd have to experiment. You could always make a class library with the master config file. Then in that library, make an accessor and in all your other projects reference that library. Then use the accessor to retrieve data. – Luke Wyatt Mar 03 '13 at 03:59
4

@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()

TylerOhlsen
  • 5,485
  • 1
  • 24
  • 39