-3

Hello I'm basically trying to make a button in my application which can delete my %appdata% folder but there's a problem it keeps saying cannot delete a read only file so i decided to do some googling but the problem still continues anyways here's my latest try still didn't work any clue?

What I'm trying to delete is %appdata%/test which also has sub folders.

   private void ClearButton_OnClick(object sender, RoutedEventArgs e)
    {
        string filepath = (Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "test"));
        //Get Currently Applied Access Control
        FileSecurity fileS = File.GetAccessControl(filepath);

        //Update it, Grant Current User Full Control
        SecurityIdentifier cu = WindowsIdentity.GetCurrent().User;
        fileS.SetOwner(cu);
        fileS.SetAccessRule(new FileSystemAccessRule(cu, FileSystemRights.FullControl, AccessControlType.Allow));

        //Update the Access Control on the File
        File.SetAccessControl(filepath, fileS);

        //Delete the file
        File.Delete(filepath);
        Process.Start(Application.ResourceAssembly.Location);
        Environment.Exit(0);
    }
MrRdy2Lose
  • 11
  • 1

3 Answers3

0

May be you need to take ownership first, if you dont have

using System.IO;
using System.IO;
using System.Security.AccessControl;
using System.Security.Principal;

//Get Currently Applied Access Control
FileSecurity fileS = File.GetAccessControl(filepath);

//Update it, Grant Current User Full Control
SecurityIdentifier cu = WindowsIdentity.GetCurrent().User;
fileS.SetOwner(cu);
fileS.SetAccessRule(new FileSystemAccessRule(cu, FileSystemRights.FullControl, AccessControlType.Allow));

//Update the Access Control on the File
File.SetAccessControl(filepath, fileS);

File.SetAttributes(filePath, FileAttributes.Normal);
File.Delete(filePath);

Also, you will need to run application with administrative privileges.

For this, Right click on your project, Add -> New Item -> Application Manifest File

then replace this line

<requestedExecutionLevel level="asInvoker" uiAccess="false" />

with this

<requestedExecutionLevel level="requireAdministrator" uiAccess="true" />

It will run your application with administrator privileges.

SimpleGuy
  • 2,764
  • 5
  • 28
  • 45
0

Try running the application with Administrative privilege .Some times C drive requires Admin privileges.

Jawad Zeb
  • 523
  • 4
  • 18
0

I was having the same issue when running my application in DEBUG mode. I was able to solve it by simply setting File.IsReadOnly = false; It then deleted with no problem.