Nikhil D
Nikhil D

Reputation: 2509

skip directories don't have required permission c#

        private int GetFileCount(DirectoryInfo directory)
        {
            int retVal = directory.GetFiles().Length;

            try
            {
                Array.ForEach(directory.GetDirectories(), dir =>
                    {
                        retVal += GetFileCount(dir);
                    });
            }
            catch (UnauthorizedAccessException ex)
            {                
                //Here stops the execution
            }

            return retVal;
        }

I have above code written when i scan through any disk drive...giving me access denied exception.. to handle the exception written catch block but it will stop the further iteration..How should continue further iteration

Upvotes: 0

Views: 57

Answers (1)

Tanima Kumari
Tanima Kumari

Reputation: 139

Inside the catch block please check if the retval is null , if yes then use the continue keyword and increment counter value. Here is a sample:

private int GetFileCount( )
    { 
            string[] subdirectories = Directory.GetDirectories(@"C:\");
            string[] result = null;

            if (subdirectories.Length > 0)
            {
                for (int i = 0; i < subdirectories.Length - 1; i++)
                {
                    try
                    {
                        result = Directory.GetFiles(subdirectories[i]);
                    }
                    catch (UnauthorizedAccessException ex)
                    {
                        if (result == null)
                        {
                            i += 1;
                            continue;
                        }
                    }
                }
            }          

        return 1;
    }

Upvotes: 1

Related Questions