Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set value in app.config - no write access to Program Files

I would like to change values in my app.config file (or rather MyProgramName.config file) at runtime. This works fine using

System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
//update values in config.AppSettings...
config.Save(ConfigurationSaveMode.Modified);

However the MyProgramName.config file is always stored in the program folder according to the documentation (https://msdn.microsoft.com/de-de/library/system.configuration.configurationuserlevel%28v=vs.110%29.aspx)

Application configuration files are in the same directory as the application and have the same name, but with a .config extension. For example, the configuration file for C:\System\Public.exe is C:\System\Public.exe.config.

Now lets assume I have some users who can not write to C:\Program Files(x86)\... (which is the default setting for non-admin users on win7). Is there a way to still use the app.config file properly or maybe place it in the %APPDATA% folder?

like image 235
H W Avatar asked Oct 20 '25 01:10

H W


1 Answers

You can use the User settings capability of the application settings api for this. These settings are stored in %userprofile%\appdata\local or %userprofile%\Local Settings\Application Data (windows version dependent).

User settings has some limitations: it is, as it says, user specific not global for all users - but presumably if you are updating values at runtime then that's what you want, otherwise you need something like this.

You essentially just have to add a .settings file, which creates the applicationSettings and/or userSettings sections in your app.config (see MSDN: How To: Create a New Setting at Design Time), create your property and set it to User, not Application, and then do this at runtime:

Properties.Settings.Default.myColor = Color.AliceBlue;
Properties.Settings.Default.Save();

The .settings property will create a user settings entry in your app.config that looks like this:

<setting name="Setting1" serializeAs="String" >
 <value>My Setting Value</value>
</setting>

You can use this to set the default value that a user session will get before any user-specific value has been saved.

Reference: MSDN: Using Application Settings and User Settings

like image 73
Andy Brown Avatar answered Oct 21 '25 16:10

Andy Brown