System.UnauthorizedAccessException when retrieving directories

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

I created a small program that compares the size of a directory with a given size. And if the directory is equal to or greater, then it registers the path to this 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 notice that the input lines long size = Convert.ToInt32(Size)come from the arguments inMain()

I read somewhere that I should not use

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

since he will immediately receive all the directories. But if I delete it, it will only receive directories in the specified path without any subdirectories. Therefore, I was told to apply recursion, but I found it to be quite complicated. I read some things on file.Attributes, about hidden files, but I did not know where to apply them.

, . D:\

, D:\ , .

, - -, .

+4
1

- . . :

    private static long maxSize = 5 * 1024 * 1024;

    static void Main(string[] args)
    {

        GetDirectorySize(new DirectoryInfo(@"d:\"));

    }

    static long GetDirectorySize(DirectoryInfo dir)
    {

        long size = 0;

        foreach(DirectoryInfo d in dir.EnumerateDirectories("*",SearchOption.TopDirectoryOnly)) {
            size += GetDirectorySize(d);
        }

        size += dir.EnumerateFiles("*",SearchOption.TopDirectoryOnly).Sum(fi => fi.Length);

        if (size > maxSize)
        {
            Console.WriteLine("Directory: {0} Size: {1}", dir, size);
        }

        return size;
    }
0

All Articles