Unhandled exception. System.UnauthorizedAccessException - C#

Shervan360 1,661 Reputation points
2023-04-06T21:18:38.5066667+00:00

Hi, Could you please help me to solve this problem? Screenshot 2023-04-06 141744

  static void Main(string[] args)
        {
            string directory = @"c:\";

            IEnumerable<string> fileNames = Directory
              .EnumerateFiles(directory, "*", SearchOption.AllDirectories);

            foreach (var item in fileNames)
            {
                Console.WriteLine(item);
            }

            //Console.ReadKey();
        }
Developer technologies .NET Other
Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Jack J Jun 25,296 Reputation points
    2023-04-07T05:21:20.7566667+00:00

    @Shervan360, Welcome to Microsoft Q&A, based on my test, I reproduced your problem. The error often means that the program does not have the permission to access the file. You could try to use the following code to ignore the Inaccessible files.

    var options = new EnumerationOptions
                {
                    IgnoreInaccessible = true,
                    RecurseSubdirectories = true,
                    
                };
                foreach (string file in Directory.EnumerateFiles("C:\\", "*.*", options))
                {
                    Console.WriteLine(  file);
                }
    

    Hope my code could help you. Best Regards, Jack


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.  


2 additional answers

Sort by: Most helpful
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2023-04-06T23:23:39.7033333+00:00

    That is expected behavior when the user running the program does not have permissions to access a folder. The following is a robust solution that recursively goes through a folder structure and catches these exceptions and reports them. Note the use of events and the code allows the user to cancel.

    internal class DirectoryOperationsSample
    {
        public static bool Cancelled;
        public delegate void OnException(Exception exception);
        /// <summary>
        /// Callback for subscribers to know about a problem
        /// </summary>
        public static event OnException OnExceptionEvent;
    
        public delegate void OnTraverseExcludeFolder(string sender);
        /// <summary>
        /// Called each time a folder is being traversed
        /// </summary>
        public static event OnTraverseExcludeFolder OnTraverseIncludeFolderEvent;
        public delegate void OnTraverse(string status);
        /// <summary>
        /// Callback for subscribers to see what is being worked on
        /// </summary>
        public static event OnTraverse OnTraverseEvent;
        public delegate void OnUnauthorizedAccessException(string message);
        /// <summary>
        /// Raised when attempting to access a folder the user does not have permissions too
        /// </summary>
        public static event OnUnauthorizedAccessException UnauthorizedAccessEvent;
        public static async Task RecursiveFolder(DirectoryInfo directoryInfo, CancellationToken cancellationToken)
        {
            
            OnTraverseEvent?.Invoke(directoryInfo.Name);
    
            DirectoryInfo folder = null;
    
            try
            {
                await Task.Run(async () =>
                {
                    foreach (DirectoryInfo dirInfo in directoryInfo.EnumerateDirectories())
                    {
    
                        folder = dirInfo;
    
                        if (
                            (folder.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden ||
                            (folder.Attributes & FileAttributes.System) == FileAttributes.System ||
                            (folder.Attributes & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint)
                        {
    
                            OnTraverseIncludeFolderEvent?.Invoke($"* {folder.FullName}");
    
                            continue;
    
                        }
    
                        OnTraverseIncludeFolderEvent?.Invoke($"{folder.FullName}");
    
                        if (!Cancelled)
                        {
                            await Task.Delay(1, cancellationToken);
                            await RecursiveFolder(folder, cancellationToken);
                        }
                        else
                        {
                            return;
                        }
    
                        if (cancellationToken.IsCancellationRequested)
                        {
                            cancellationToken.ThrowIfCancellationRequested();
                        }
    
                    }
    
                }, cancellationToken);
    
            }
            catch (Exception exception)
            {
                switch (exception)
                {
                    case OperationCanceledException _:
                        Cancelled = true;
                        break;
                    case UnauthorizedAccessException _:
                        UnauthorizedAccessEvent?.Invoke($"Access denied '{exception.Message}'");
                        break;
                    default:
                        OnExceptionEvent?.Invoke(exception);
                        break;
                }
            }
        }
    }
    
    

    To learn more see these samples

    0 comments No comments

  2. Castorix31 90,681 Reputation points
    2023-04-08T07:48:47.5566667+00:00

    To get rights and avoid UnauthorizedAccessException , you can add a Manifest with requireAdministrator (https://www.c-sharpcorner.com/blogs/how-to-force-my-net-application-to-run-as-administrator-using-uac)

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.