title: C# winform delete folders and files on uninstall. Permission Error
body: <p>I am getting the below error.</p>
  
  <p>I need to uninstall the app and delete all files and folders created either by the application or users in the program files/myapp.</p>
  
  <p>How can I resolve this issue?
  Thanks.</p>
  
  <pre><code>Access to the path 'C:\Program Files (x86)\DefaultProgram\Application\app.exe' is denied.
  </code></pre>
  
  <p>My Code:</p>
  
  <pre><code>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);
          } 
  </code></pre>