2

The following code works on Windows XP and Windows 7:

var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings.Remove(key);
config.AppSettings.Settings.Add(key, value);
config.Save(ConfigurationSaveMode.Modified); // fails here

But it's causing an Access to Path denied error on Windows 8. I've tried changing the ConfigurationUserLevel to PerUserRoamingAndLocal but it doesn't do anything.

What do I need to do in order to be able to update the App.Config (or specifically, [application_name].exe.config in Windows 8?

I should add that the user trying running the app has the default Windows 8 privileges. I don't know exactly what that is, but it's pretty low. Does this need to be elevated in order for this to work?

Edit: The logged error:

<Message>Access to the path 'C:\ProgramData\Path\AppName.exe.config' is denied.</Message>
<StackTrace>   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)
   at System.Configuration.Internal.WriteFileContext.ValidateWriteAccess(String filename)
   at System.Configuration.Internal.WriteFileContext.Complete(String filename, Boolean success)
   at System.Configuration.Internal.InternalConfigHost.StaticWriteCompleted(String streamName, Boolean success, Object writeContext, Boolean assertPermissions)
   at System.Configuration.Internal.InternalConfigHost.System.Configuration.Internal.IInternalConfigHost.WriteCompleted(String streamName, Boolean success, Object writeContext, Boolean assertPermissions)
   at System.Configuration.Internal.InternalConfigHost.System.Configuration.Internal.IInternalConfigHost.WriteCompleted(String streamName, Boolean success, Object writeContext)
   at System.Configuration.Internal.DelegatingConfigHost.WriteCompleted(String streamName, Boolean success, Object writeContext)
   at System.Configuration.UpdateConfigHost.WriteCompleted(String streamName, Boolean success, Object writeContext)
   at System.Configuration.MgmtConfigurationRecord.SaveAs(String filename, ConfigurationSaveMode saveMode, Boolean forceUpdateAll)
   at System.Configuration.Configuration.SaveAsImpl(String filename, ConfigurationSaveMode saveMode, Boolean forceSaveAll)
   at System.Configuration.Configuration.Save(ConfigurationSaveMode saveMode)
   at MyNamespace.Infrastructure.ConfigurationManager.WriteToAppSettings(String key, String value) in C:\Path\To\App\AppName\Infrastructure\ConfigurationManager.cs:line 76
</StackTrace>
DaveDev
  • 41,155
  • 72
  • 223
  • 385

2 Answers2

4

Can you post the exception message?

I just tested your code on Win 8 Pro, VS 2012 and it works fine.

var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings.Remove("my_new_key");
config.AppSettings.Settings.Add("my_new_key", "my new value");
config.Save(ConfigurationSaveMode.Modified); 

yields a config file of

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <appSettings>
        <add key="my_new_key" value="my new value" />
    </appSettings>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
</configuration>

As far as requiring elevated privileges, it depends on which user the application is running under and what the permissions are set to for the file/directory where your config file lives.

If you use the default project location %homepath%\documents\visual studio 2012\projects\, then you would not need to run the application with elevated privileges in order to edit the exe.config file.

If your file lives anywhere else, then you'll have to take a look at the privileges of that file (right click -> properties -> security tab) .. and see if the user running the application (likely your account) has write privileges.

This is a great explanation on NTFS file permissions. http://www.techrepublic.com/article/windows-101-know-the-basics-about-ntfs-permissions/6084446

Derek Curtis
  • 639
  • 6
  • 14
  • I've updated the question with the exception message & stacktrace. – DaveDev Dec 04 '12 at 11:13
  • Just from looking at the path, C:/ProgramData is read-only by default to all but the built in SYSTEM account and Administrators group. Running under elevated privileges would fix your problem OR you can explicitly give your user account permission to edit the file. I would probably go the route of explicitly giving yourself privileges. – Derek Curtis Dec 04 '12 at 11:23
  • Can the application automatically give explicit permission to the user account, or is that something that will have to be set manually? When this app is deployed it's going to non-tech-savvy users so I need to make this as streamlined as possible. If there's no way to do this automatically I'll have to put that config data somewhere else. – DaveDev Dec 04 '12 at 11:36
  • This post shows how to have the application request elevated permissions when your program runs. http://stackoverflow.com/questions/133379/elevating-process-privilege-programatically If you don't want to do that, the easiest solution is going to be to install the application somewhere, where the user would have privileges to edit the file (In their home directory somewhere, though this isn't a standard location). Otherwise, you'll need to include something like SubInACL (http://www.microsoft.com/en-us/download/details.aspx?id=23510) with your application and run a post installation script. – Derek Curtis Dec 04 '12 at 12:09
1

Try this to remove the key:

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

AppSettingsSection appSettings = (AppSettingsSection)config.GetSection("appSettings");
appSettings.Settings.Remove("ConnectionString");
appSettings.Settings.Add("ConnectionString", "");

config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection(config.AppSettings.SectionInformation.Name);

or to change the key value:

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
KeyValueConfigurationCollection settings = config.AppSettings.Settings;

settings["KeyName"].Value = "newkeyvalue";

config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection(config.AppSettings.SectionInformation.Name);
Matija Grcic
  • 12,963
  • 6
  • 62
  • 90