-1

Every time I run the code below, I get an UnauthorizedAccessException. I added try and catch blocks, which prevented the error, but it stopped the program dead in it's tracks.

Is there a way I can ignore this error and read the Unauthorized Access files? If not, I would just like my program to skip these files continue without stopping.

Here is the code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Threading;

namespace Interface
{
    class Progra
    {
        static void Main(string[] args)
        {
            try
            {
                int number = 0;
                string[] files = Directory.GetFiles("C:\\", "*.*", 
                    SearchOption.AllDirectories);

                foreach (string file in files)
                {
                    number = number + 1;

                    Console.ForegroundColor = ConsoleColor.Green;
                    DateTime now = DateTime.Now;
                    Console.Write("[" + now + "]");

                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.Write(" [" + number + "] ");

                    Console.ForegroundColor = ConsoleColor.White;
                    Console.Write(file + "\n");
                }

                Console.WriteLine("");
                Console.WriteLine("- " + number + " files found!");
                Console.ReadKey();
            }
            catch
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.Write("- An unknown error occoured and the contents " + 
                    "of this folder can not be displayed.\n");
                Console.ForegroundColor = ConsoleColor.White;
            }

            Console.ReadKey();
        }
    }
}

If there is an answer, can you show me how I can do it? Noob at C# :P .

  • 2
    Are you running that as administrator? It probably fails on some C:\Windows file/folder – Camilo Terevinto May 03 '18 at 23:56
  • I did try that. But it eventually came across the same error with a different file... :/ – RedstoneUmbreon May 03 '18 at 23:57
  • 4
    Possible duplicate of [Ignore folders/files when Directory.GetFiles() is denied access](https://stackoverflow.com/questions/172544/ignore-folders-files-when-directory-getfiles-is-denied-access) – Rufus L May 04 '18 at 00:00
  • Heres another one https://stackoverflow.com/questions/1393178/unauthorizedaccessexception-cannot-resolve-directory-getfiles-failure – TheGeneral May 04 '18 at 00:01
  • The line string[] files = Directory.GetFiles("C:\\", "*.*", SearchOption.AllDirectories); throws the exeption. – RedstoneUmbreon May 04 '18 at 00:02
  • With "C:\\" and filter `All`, you are trying to access folders you might not has permission to browse/access. You should use [`WindowsIdentity.GetCurrent()`](https://msdn.microsoft.com/en-us/library/sfs49sw0(v=vs.110).aspx) to get the User ACL Identity, then, [`Directory.GetAccessControl()`](https://msdn.microsoft.com/en-us/library/c1f66bc2(v=vs.110).aspx), to verify if the User rights meet the [`AuthorizationRule`](https://msdn.microsoft.com/en-us/library/system.security.accesscontrol.authorizationrule(v=vs.110).aspx) required. – Jimi May 04 '18 at 00:05
  • Jimi, can you show me how to do that? I'm kind of a noob at C#. :P – RedstoneUmbreon May 04 '18 at 00:06
  • Well, you have already 2 possible solutions in the aswers that has been linked here. I have posted something like this. You can see it here: [Directory.GetFiles() throws UnauthorizedAccessException on system directory with localized name](https://stackoverflow.com/questions/49460269/directory-getfiles-throws-unauthorizedaccessexception-on-system-directory-with?answertab=active#tab-top). But the answer has never been accepted, so (probably) I'm the only one who tested it. If you want, test it yourself and let me know. – Jimi May 04 '18 at 00:41

1 Answers1

0
try
{
    int number = 0;
    string[] files = Directory.GetFiles("C:\\", "*.*",
        SearchOption.TopDirectoryOnly);

    foreach (string file in files)
    {
        try
            {
                string[] innerFiles = Directory.GetFiles(file, "*.*",
                    SearchOption.TopDirectoryOnly);
            }
            catch (Exception e)
            {
                // stuff here
            }

            number = number + 1;

            Console.ForegroundColor = ConsoleColor.Green;
            DateTime now = DateTime.Now;
                Console.Write("[" + now + "]");

                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.Write(" [" + number + "] ");

                Console.ForegroundColor = ConsoleColor.White;
                Console.Write(file + "\n");
            }

            Console.WriteLine("");
            Console.WriteLine("- " + number + " files found!");
            Console.ReadKey();
        }
        catch (Exception e)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.Write("- An unknown error occoured and the contents " +
                "of this folder can not be displayed.\n");
            Console.ForegroundColor = ConsoleColor.White;
        }

        Console.ReadKey();
    }

That is a good amount of work, but I kind of got you started a little bit. The exception was happening with the declaration of the string array, once this happened it never entered the foreach loop and just ended. If you want it to continue the loop after failing move the exception to the inside of the loop, this way the catch will happen and go back through the loop. Other thing you will need to do is make it recursive, loop through each level in the file structure instead of grabbing all the files at one time. To be honest the method for getting the files from Microsoft isn't very good...it should probably just take care of this for you but I'm sure there was a reason it doesn't.

I am not sure what the program is for but you will likely need to distinguish between files and directories at some point in the foreach loop.

Keith
  • 98
  • 4
  • It's just to count and list the number of files in your system. Just for the fun of it. :) – RedstoneUmbreon May 04 '18 at 01:09
  • If you are testing out, do not try to list out all files in director you are not familiar with. For me, if I want to `Directory.GetFiles`, I would just test out in a directory that I create. For sure, I will know what the expected output would be. If you try in any other directory, you may not know what the expected result. – Just a HK developer May 04 '18 at 01:18