简体   繁体   中英

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?

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

Data, stored in app.config , are not intended for changing by regular user at run-time. Do not write a code, which re-writes app.config , except the case, when this code is located at some config application for admin. Use application settings instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM