以编程方式向WPF中的文件添加写权限

在我的WPF MVVM应用程序中,我有一个要修改的XML文件。 它在Visual Studio中成功运行。 但它在运行已安装的应用程序时显示错误。 如何通过代码设置权限..

我用过这段代码,

// current security settings. FileSecurity fSecurity = File.GetAccessControl(FilePath); // Add the FileSystemAccessRule to the security settings. string rr = WindowsIdentity.GetCurrent().Name; fSecurity.AddAccessRule(new FileSystemAccessRule(WindowsIdentity.GetCurrent().Name, FileSystemRights.FullControl, AccessControlType.Allow)); // Set the new access settings. File.SetAccessControl(FilePath, fSecurity); 

仍然无法解决问题…,

提前致谢..

看到例外……

System.UnauthorizedAccessException:尝试执行未经授权的操作。 在System.Security.AccessControl.NativeObjectSecurity.Persist的System.Security.AccessControl.Win32.SetSecurityInfo(ResourceType类型,字符串名称,SafeHandle句柄,SecurityInfos securityInformation,SecurityIdentifier所有者,SecurityIdentifier组,GenericAcl sacl,GenericAcl dacl)处(String name,SafeHandle)在System.Security的System.Security.AccessControl.NativeObjectSecurity.Persist(String name,AccessControlSections includeSections)处的System.Security.AccessControl.NativeObjectSecurity.Persist(String name,AccessControlSections includeSections,Object exceptionContext)处理,AccessControlSections includeSections,Object exceptionContext。 System.IO.File.SetAccessControl上的AccessControl.FileSystemSecurity.Persist(String fullPath)(String path,FileSecurity fileSecurity)

要设置权限大多需要高级用户权限(假设您正在运行Windows 7)。

要进行上述validation,请将Visual Studio作为“以管理员身份运行”启动并调试您的代码。

什么是确切的exception消息?

以下是工作示例:它为用户组EveryOne设置完全权限

 private static void WriteAcl ( string filename ) { //Set security for EveryOne Group SecurityIdentifier sid =new SecurityIdentifier(WellKnownSidType.WorldSid, null); IdentityReference userIdentity =sid.Translate (typeof(NTAccount)); var AccessRule_AllowEveryOne = new FileSystemAccessRule ( userIdentity, FileSystemRights.FullControl, AccessControlType.Allow ); var securityDescriptor = new FileSecurity (); securityDescriptor.SetAccessRule ( AccessRule_AllowEveryOne ); File.SetAccessControl ( filename, securityDescriptor ); } 

仅当“用户帐户设置”设置为“从不通知”时,此代码才有效。 看起来它在你的电脑上打开了吗?

解决方法是使用Application Manifest以超级用户身份启动应用程序。

http://msdn.microsoft.com/en-us/library/bb756929.aspx