Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an Application Settings shared to all users that could be changed at run time

I need some setting of an application that will be shared among all users of the computer, but could also be changed at at run time. That seam simple, but according to the Application Settings MSDN article, it's either one or the other.

There are two types of application settings, based on scope:

  • Application-scoped settings can be used for information such as a URL for a Web service or a database connection string. These values are associated with the application. Therefore, users cannot change them at run time.

  • User-scoped settings can be used for information such as persisting the last position of a form or a font preference. Users can change these values at run time.

I could write code to edit the app.config XML file, but since it's located in the program directory, it's protected under windows 7. So this is not possible without elevating the program or playing with NTFS rights.

So I need the configuration file to be written in a common folder like System.Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData).

But this is a fairly common requirement!

So, I'm wondering if there a simple way of achieving this without reinventing the wheel, or if I have to write my own Setting Manager.

like image 261
DavRob60 Avatar asked Apr 30 '13 18:04

DavRob60


2 Answers

After reading the answers here and playing with the ConfigurationManager.Open methods I ended up with the following:

string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "MyApp", "MyApp.config");
Configuration MyAppConfig = ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap { ExeConfigFilename = path }, ConfigurationUserLevel.None);

The nice part is the file doesn't have to exist, and if you call Save() on it, it will create the folder and the file for you. AppSettings["key"] didn't work though so I had to use

MyAppConfig.AppSettings.Settings["key"].Value

to read and write an existing value and

MyAppConfig.AppSettings.Settings.Add("key", value)

to add a new value.

like image 123
AlexDev Avatar answered Oct 08 '22 21:10

AlexDev


I have had a similar problem and ended up writing my own settings class. It was very basic. I created a Settings class with the properties I needed, and a SettingsManager with Save() and Load() methods that simply serialized/deserialized the object via XmlSerializer into/from a file.

Yes, it is your own code, but it is very simple code, takes less time than trying to figure out whether there is a component providing what you need and how to customize it.

like image 4
gabnaim Avatar answered Oct 08 '22 22:10

gabnaim