3

From my program I want to delete folders with or without files/folders in them.

Code:

    static void Main(string[] args)
    {
        List<string> foldersToDelete = new List<string>();

        foreach(var f in System.IO.Directory.GetDirectories(@"C:\Users\Public\MySpecialTempFolder"))
        {
            var dir = new DirectoryInfo(f);
            dir.Attributes = dir.Attributes & ~FileAttributes.ReadOnly;

            long size = GetDirectorySize(f);

            // delete folders less then 1 mb
            if (size < 1000000)
                foldersToDelete.Add(f);
        }

        foreach (var s in foldersToDelete)
            System.IO.Directory.Delete(s, true);
    }

    private static long GetDirectorySize(string folderPath)
    {
        DirectoryInfo di = new DirectoryInfo(folderPath);
        return di.EnumerateFiles("*.*", SearchOption.AllDirectories).Sum(fi => fi.Length);
    }

However... when I run this i get Access denied. Whats wrong, I can do this manually by right-click on the folder and delete it right there and then

Jason94
  • 13,320
  • 37
  • 106
  • 184
  • 1
    Are you running VS as admin? – Jonathan Carroll Oct 07 '15 at 17:16
  • 1
    Possible duplicate of [File.Delete Access to the path is denied](http://stackoverflow.com/questions/15260146/file-delete-access-to-the-path-is-denied) – Nasreddine Oct 07 '15 at 17:38
  • You should post the the exception you're getting along with the stack trace because if you're getting an `UnauthorizedAccessException` then according to the [documentation](https://msdn.microsoft.com/en-us/library/fxeahc5f%28v=vs.110%29.aspx) it means that "The caller does not have the required permission.". Other than that your code seems correct. – Nasreddine Oct 07 '15 at 17:43

4 Answers4

2

Try the Visual Basic delete:

var directory = new DirectoryInfo(targetDir);
if (directory.Exists)
{
    Microsoft.VisualBasic.FileIO.FileSystem.DeleteDirectory(targetDir, Microsoft.VisualBasic.FileIO.DeleteDirectoryOption.DeleteAllContents);
}

From File.Delete Access to the path is denied

Community
  • 1
  • 1
Seth Kitchen
  • 1,526
  • 19
  • 53
1

You can try to force your program to run with eleveted privelegies to do so right-click on your Project Properties directory -> Add New Item and then choose Application Manifest File.

In manifest file you will find the tag requestedExecutionLevel you may set the level to three values.

Set it to :

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

And make sure that your project use your new manifest file in Properties menu

Fabjan
  • 13,506
  • 4
  • 25
  • 52
1

I've always used this function to delete a folder and its contents. This will work as long as you have the correct permissions for the folder. Remember to add using System.IO; to use this function.

private void DeleteDirectory(string path)
{
    if (Directory.Exists(path))
    {
        //Delete all files from the Directory
        foreach (string file in Directory.GetFiles(path))
        {
            File.Delete(file);
        }
        //Delete all child Directories
        foreach (string directory in Directory.GetDirectories(path))
        {
            DeleteDirectory(directory);
        }
        //Delete a Directory
        Directory.Delete(path);
        }
    }
}

Found from this site: http://www.aspsnippets.com/Articles/Delete-all-Directories-Folders-and-Subdirectories-Subfolders-Recursively-using-C-and-VBNet.aspx

ivp17
  • 11
  • 2
0

If running VS as admin doesn't work, you may need to remove attributes from the directory and files before deleting.

Taken from here https://stackoverflow.com/a/1702920/3922214 :

Conclusion: always remove all dir,file attributes diffrent then Normal before deleting. So below code solve the problem:

System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(@"E:\3\{90120000-0021-0000-0000-0000000FF1CE}-C1");

if (dir.Exists)
{
    setAttributesNormal(dir);
    dir.Delete(true);
}

. . .

private void setAttributesNormal(DirectoryInfo dir)
{
    foreach (string subDirPath in dir.GetDirectories())
    {
        setAttributesNormal(new DirectoryInfo(subDirPath));
    }
    foreach (string filePath in dir.GetFiles()) 
    {
        var file = new FileInfo(filePath)
        file.Attributes = FileAttributes.Normal;
    }
}
Community
  • 1
  • 1
Jonathan Carroll
  • 880
  • 1
  • 5
  • 20