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