以下代码适用于 Windows XP 和 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
但这会导致 Windows 8 上的 Access to Path denied 错误。我尝试将其更改为ConfigurationUserLevel
,PerUserRoamingAndLocal
但它没有做任何事情。
我需要做什么才能更新 App.Config(或者具体来说,Windows 8 中的 [application_name].exe.config?
我应该补充一点,尝试运行该应用程序的用户具有默认的 Windows 8 权限。我不知道那是什么,但它非常低。是否需要提升才能使其正常工作?
编辑: 记录的错误:
<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>