我收到以下錯誤。C#winform刪除卸載文件夾和文件。權限錯誤
我需要卸載應用程序並刪除應用程序或用戶在程序文件/ myapp中創建的所有文件和文件夾。
我該如何解決這個問題? 謝謝。
Access to the path 'C:\Program Files (x86)\DefaultProgram\Application\app.exe' is denied.
我的代碼:
protected override void OnAfterUninstall(IDictionary savedState)
{
string sFolder = Path.GetDirectoryName(Context.Parameters["assemblypath"]);
string sUsername = "NT AUTHORITY\\LOCALSERVICE";
DirectoryInfo myDirectoryInfo = new DirectoryInfo(sFolder);
DirectorySecurity myDirectorySecurity = myDirectoryInfo.GetAccessControl();
myDirectorySecurity.AddAccessRule(
new FileSystemAccessRule(
sUsername, FileSystemRights.Read |
FileSystemRights.Write |
FileSystemRights.Modify, InheritanceFlags.ContainerInherit |
InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, AccessControlType.Allow));
myDirectoryInfo.SetAccessControl(myDirectorySecurity);
base.OnAfterUninstall(savedState);
string appPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
DeleteDirectory(Path.Combine(appPath, "DB"));
DeleteDirectory(appPath);
}
public static void DeleteDirectory(string target_dir)
{
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);
}
運行時無法刪除exe。 –
app.exe未運行... – kyusan93
錯誤來自DeleteDirectory(appPath); – kyusan93