卸载时,尝试删除目录时出现 IOException。'目录不为空'。我尝试了下面列出的不同方法,但没有任何效果。留下(且无法删除)的文件具有不同的所有者。可以删除的文件的所有者为“SYSTEM”。引发异常的文件的所有者“管理员(PC_Name\Administrators)”“系统”文件已由 installshield 安装程序 (MSI) 编写,而其他文件由我的应用程序编写,由 installshield 启动并提升为管理员...
如何强制删除此文件夹/文件?
//http://stackoverflow.com/questions/329355/cannot-delete-directory-with-directory-deletepath-true
public static bool DeleteDirectory(string target_dir)
{
bool result = false;
string[] files = Directory.GetFiles(target_dir);
string[] dirs = Directory.GetDirectories(target_dir);
foreach (string file in files)
{
File.SetAttributes(file, FileAttributes.Normal);
File.Delete(file);
}
foreach (string dir in dirs)
{
DeleteDirectory(dir);
}
Directory.Delete(target_dir, false);
return result;
}
//http://stackoverflow.com/questions/611921/how-do-i-delete-a-directory-with-read-only-files-in-c
private static void DeleteFileSystemInfo(FileSystemInfo fsi)
{
fsi.Attributes = FileAttributes.Normal;
var di = fsi as DirectoryInfo;
if (di != null)
{
foreach (var dirInfo in di.GetFileSystemInfos())
DeleteFileSystemInfo(dirInfo); }
fsi.Delete();
}
//http://stackoverflow.com/questions/611921/how-do-i-delete-a-directory-with-read-only-files-in-c
public static void ForceDeleteDirectory(string path)
{
DirectoryInfo root;
Stack<DirectoryInfo> fols;
DirectoryInfo fol;
fols = new Stack<DirectoryInfo>();
root = new DirectoryInfo(path);
fols.Push(root);
while (fols.Count > 0)
{
fol = fols.Pop();
fol.Attributes = fol.Attributes & ~(FileAttributes.Archive | FileAttributes.ReadOnly | FileAttributes.Hidden);
foreach (DirectoryInfo d in fol.GetDirectories())
{
fols.Push(d);
}
foreach (FileInfo f in fol.GetFiles())
{
f.Attributes = f.Attributes & ~(FileAttributes.Archive | FileAttributes.ReadOnly | FileAttributes.Hidden);
f.Delete();
}
}
root.Delete(true);
}
编辑:对不起,忘了这个:
在出现问题的文件夹上,在安装时,我将完全控制“用户”帐户:
System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(
System.Security.Principal.WellKnownSidType.BuiltinUsersSid, null);
System.Security.Principal.NTAccount acct = sid.Translate(typeof(System.Security.Principal.NTAccount))
as System.Security.Principal.NTAccount;
string usr = acct.ToString();
DirectoryInfo info = new DirectoryInfo(dir);
DirectorySecurity ds = info.GetAccessControl();
ds.AddAccessRule(new FileSystemAccessRule(usr, FileSystemRights.FullControl, AccessControlType.Allow));
ds.AddAccessRule(new FileSystemAccessRule(usr, FileSystemRights.FullControl,
InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.InheritOnly,
AccessControlType.Allow));
info.SetAccessControl(ds);