在 Windows 7 中删除受保护的文件夹






4.82/5 (13投票s)
在 Windows 7 中删除受保护的文件夹
最近我遇到了一些麻烦,试图删除之前 Windows 安装留下的大量文件夹。例如 d:\temp\windows d:\temp\program files ... 这与所有权和访问权限有关。运行这个程序解决了问题。也许有人会想进一步完善它,并将其制作成一个真正的实用工具。
请自行承担风险,此程序对您的硬盘具有致命影响
class Program
{
static void Main(string[] args)
{
var path = args[0];
DeleteFolder(new System.IO.DirectoryInfo(path));
}
private static void DeleteFolder(DirectoryInfo directoryInfo)
{
GrantAccess(directoryInfo.FullName);
try
{
foreach (DirectoryInfo d in directoryInfo.GetDirectories())
{
DeleteFolder(d);
}
}
catch { }
try
{
foreach (FileInfo f in directoryInfo.GetFiles())
{
GrantAccess(f.FullName);
try
{
f.Delete();
Console.WriteLine("Deleted File {0}", f.FullName);
}
catch { }
}
}
catch { }
try
{
directoryInfo.Delete(true);
Console.WriteLine("Deleted Folder {0}", directoryInfo.FullName);
}
catch { }
}
private static void GrantAccess(string filepath)
{
var fs = File.GetAccessControl(filepath);
var sid = fs.GetOwner(typeof(SecurityIdentifier));
var ntAccount = new NTAccount(Environment.UserDomainName, Environment.UserName);
try
{
var currentRules = fs.GetAccessRules(true, false,typeof(NTAccount));
foreach (var r in currentRules.OfType<FileSystemAccessRule>())
{
Console.WriteLine(r.AccessControlType + " " + r.FileSystemRights);
}
var newRule = new FileSystemAccessRule(
ntAccount, FileSystemRights.FullControl,
AccessControlType.Allow);
fs.AddAccessRule(newRule);
File.SetAccessControl(filepath, fs);
}
catch { }
finally { fs=null; sid=null; ntAccount=null;}
}
}
----------------------- 我建议在函数中添加 finally{fs=null; sid=null; ntAccount=null;}
,以确保获得如此强大文件系统控制权的那些对象能够尽快在任何情况下被释放/终结。(由 Alex Bell 添加)