Search code examples
c#wpfwindows-installerconnection-stringadministrator

WPF - Modify Configuration settings during runtime


I'm creating a WPF application. It works fine in Visual Studio. But, whenever I modify configuration settings through application after installation, It throws error 'Error occurred loading a configuration file: Access to path c:\Program Files (x86)\… denied'. I can't run the program as Admin every time as per requirement. Is there any way to solve this?

var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");connectionStringsSection.ConnectionStrings["cn"].ConnectionString = "data source=" + txtServer.Text + ";database=" + txtDatabase.Text + ";User ID=" + txtUserID.Text + ";Password=" + pwdPassword.Password;
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("connectionStrings");

config.Save(ConfigurationSaveMode.Modified);

// Force a reload of the changed section.
ConfigurationManager.RefreshSection("appSettings");

Solution

  • Rule of thumb: Treat your installation folder under program files as read-only.

    That is really all there is to it. I have this list of approaches to deal with access denied. Most options there are bad and listed so one can remember why they are bad (I just updated the linked answer with color to indicate more recommended approaches - it is a bit messy, but at least it can spark ideas).

    Go for move file to writable location, or use internal defaults only, or better yet read from the cloud (database) and write to userprofile if you need to.

    The traditional way is obviously the registry with HKCU entries.

    (I like the "versioning and backup of settings" made possible by database storage of settings as opposed to just settings files - more work though).