Unauthorized Exception in Windows Forms - C #

I am trying to delete a file present in "filePath" through code. But when I try to delete the file, I get an "unauthorized exception". I know that this is because I do not have access to delete the file. Then I wrote the SetAccessRule method. But, unfortunately, this did not help me. Any help would be really appreciated.

public bool deleteAppExecutable(string filePath) { try { if (File.Exists(filePath)) { SetAccessRule(filePath); File.SetAttributes(filePath, FileAttributes.Normal); File.Delete(filePath); } return true; } catch (Exception ex) { return false; } } public void SetAccessRule(string filePath) { // Create a new DirectoryInfo object. DirectoryInfo dInfo = new DirectoryInfo(filePath); // Get a DirectorySecurity object that represents the // current security settings. DirectorySecurity dSecurity = dInfo.GetAccessControl(); // Add the FileSystemAccessRule to the security settings. dSecurity.AddAccessRule(new FileSystemAccessRule(Environment.UserName, FileSystemRights.Delete, AccessControlType.Allow)); // Set the new access settings. dInfo.SetAccessControl(dSecurity); } 
0
source share

Source: https://habr.com/ru/post/1209723/


All Articles