获取文件c#的所有权

我试图取得一个文件的所有权,并通过C#删除它。 该文件是iexplorer.exe,默认为当前所有者 – TrustedInstaller。 FileSecurity.SetOwner方法似乎设置了指定的所有权,但实际上并没有更改初始所有者并且不会抛出任何exception。 显然,下一次删除文件的尝试会引发exception。 在代码中应该更改什么来获取文件的所有权并将其删除?

var fileS = File.GetAccessControl(@"C:\Program Files (x86)\Internet Explorer\iexplore.exe"); fileS.SetOwner(new System.Security.Principal.NTAccount(Environment.UserDomainName, Environment.UserName)); File.Delete(@"C:\Program Files (x86)\Internet Explorer\iexplore.exe"); 

您必须明确启用SeTakeOwnershipPrivilege

必须获取对象的所有权而不被授予自由访问权限。 此权限允许将所有者值仅设置为持有者可合法分配为对象所有者的值。 用户权限:获取文件或其他对象的所有权。

我建议你阅读Mark Novak撰写的精彩文章: 可靠,安全,高效地管理托管代码中的权限 。

和/或看看他的样本 。

更新

用法示例:

 var fileS = File.GetAccessControl(@"C:\Program Files (x86)\Internet Explorer\iexplore.exe"); Privilege p; bool ownerChanged = false; try { p = new Privilege(Privilege.TakeOwnership); p.Enable(); fileS.SetOwner(new System.Security.Principal.NTAccount( Environment.UserDomainName, Environment.UserName)); ownerChanged = true; } catch(PrivilegeNotHeldException e) { // privilege not held // TODO: show an error message, write logs, etc. } finally { p.Revert(); } if (ownerChanged) File.Delete(@"C:\Program Files (x86)\Internet Explorer\iexplore.exe"); 
  string filepath = @"C:\Program Files (x86)\Internet Explorer\iexplore.exe"; //Get Currently Applied Access Control FileSecurity fileS = File.GetAccessControl(filepath); //Update it, Grant Current User Full Control SecurityIdentifier cu = WindowsIdentity.GetCurrent().User; fileS.SetOwner(cu); fileS.SetAccessRule(new FileSystemAccessRule(cu, FileSystemRights.FullControl, AccessControlType.Allow)); //Update the Access Control on the File File.SetAccessControl(filepath, fileS); //Delete the file File.Delete(filepath); 

添加以下导入

  using System.IO; using System.Security.AccessControl; using System.Security.Principal; 

以高架模式运行代码。

使用示例中的类权限在Windows 8.1中提供支持: 可靠,安全,高效地管理托管代码中的权限

  private bool TryDeleteFile(string fileName) { string filePath = Path.GetFullPath(fileName); var fi = new FileInfo(filePath); bool ownerChanged = false; bool accessChanged = false; bool isDelete = false; FileSecurity fs = fi.GetAccessControl(); Privilege p = new Privilege(Privilege.TakeOwnership); try { p.Enable(); fs.SetOwner(WindowsIdentity.GetCurrent().User); File.SetAccessControl(filePath, fs); //Update the Access Control on the File ownerChanged = true; } catch (PrivilegeNotHeldException ex) { } finally { p.Revert(); } try { fs.SetAccessRule(new FileSystemAccessRule(WindowsIdentity.GetCurrent().User, FileSystemRights.FullControl, AccessControlType.Allow)); File.SetAccessControl(filePath, fs); accessChanged = true; } catch (UnauthorizedAccessException ex) { } if (ownerChanged && accessChanged) { try { fi.Delete(); isDelete = true; } catch (Exception ex) { } } return isDelete; }