我试图把文件的所有权,并通过C#中删除。 该文件默认IEXPLORER.EXE,目前的拥有者 - 的TrustedInstaller。 该方法FileSecurity.SetOwner似乎设置指定的所有权,但实际上并没有改变最初的拥有者和抛出也不例外。 显然,下一次尝试删除该文件抛出异常。 我应该在代码改为采取文件的所有权,并删除它?
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
:
需要采取的对象的所有权不被授予任意访问。 该特权允许所有者值被设置为仅那些,所述保持器可以合理地分配作为一个对象的所有者的值。 用户权限:以文件或其他对象的所有权。
我建议你阅读马克·诺瓦克写的大文章: 在托管代码操纵特权可靠,安全,高效 。
和/或看看他的样品 。
更新
实例:
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;
}