System.UnauthorizedAccessException when getting directories

Viewed 632

I am really new to C#, so I've been working on a small pet project.

I've created a small program that compares the size of a directory with a given size. And if the directory is equal or larger, then it logs the path to that directory.

long size = Convert.ToInt32(Size) * 1024 * 1024;
string[] directories = Directory.GetDirectories(path, "*", SearchOption.AllDirectories); //the error occurs on this line
Array.Sort(directories);

foreach (string name in directories)
   try
   {
      DirectoryInfo directory = new DirectoryInfo(name);
      long dir = directory.EnumerateFiles("*", SearchOption.AllDirectories).Sum(fi => fi.Length);

   if (dir >= ScanSize)
      Console.WriteLine(directory);
   }

   catch (UnauthorizedAccessException) {  }

I should note that the input strings, and the long size = Convert.ToInt32(Size) come from the arguments in the Main()

I've read somewhere that I shouldn't use

Directory.GetDirectories(ScanPath, "*", SearchOption.AllDirectories);

since it'll get all the directories at once. But if I remove it, it only gets the directories in the given path, without any subdirectories. So I was told to apply recursion, but I found these fairly difficult. I read some things on file.Attributes, about hidden files, but I didn't know where to apply them.

I am the administrator of the system and I plan to run this on the entire data drive. D:\

But in this case the error occurs when the program tries to access the trash can of the D:\ But even if it skips this specific location, the error still comes back at another inaccessible one.

I'm hoping anyone here knows a good example or knows a website that explains this.

1 Answers
Related