Search code examples
c#recursionerror-handlingreturnboolean

Error handling is interfering with the Recursive method in C#


I am creating a list of files that are in a directory. Before that list is made I first want to do error checking to make sure the directory that is entered in the console app is valid. I am using recursion to create a loop so that if the directory is invalid it will run back through the validation method.

From my Program.cs class I start with the GetFileListFromDirectory method. That method then goes to the IsValidDirectory method. If I enter a good directory path the first time everything works fine. When I test with a bad directory though my input runs through the IsValidDirectory method correctly and gives me an error; so I enter a new directory in the console and the method loops back to the beginning of IsValidDirectory (like it should) and validates the new directory is correct but when it gets to the return it then jumps back to the Catch line IsValidDirectory with the original bad directory. After it does this it then returns to GetFileListFromDirectory and is stuck in the while loop because isValid is still false when it should actually be true at this point.

Thanks for the help!

/* Creates a list of all of the files in the chosen directory for mass audit potential */
        public List<string> GetFileListFromDirectory(string inputDirectory)
        {
            bool isValid = false; //makes sure the directory is validated before continuing the method

            while (!isValid)
            {
                isValid = IsValidDirectory(inputDirectory);
            }

            DirectoryInfo directory = new DirectoryInfo(inputDirectory);
            FileInfo[] folder = directory.GetFiles("*");

            List<string> files = new List<string>();

            if (isValid)
            {
                foreach (var file in folder)
                {
                    files.Add(file.Name.ToString().Replace(".csv", "").Replace(".txt", ""));
                }

                return files;
            }

            return null; //code path does not allow this return
        }

        /* Method keeps looping back to GetFileListFromDirectory if the directory results in error */
        public bool IsValidDirectory(string inputDirectory)
        {
            bool validDirectory;

            try
            {
                DirectoryInfo directory = new DirectoryInfo($@"{inputDirectory}");
                FileInfo[] folder = directory.GetFiles("*");

                validDirectory = true;
            }
            catch(Exception e)
            {
                Console.WriteLine($"\n{e}\n\nCheck the directory path and enter it again: ");

                IsValidDirectory(Console.ReadLine());

                validDirectory = false;
            }

            return validDirectory;
        }

Solution

  • Rather than calling IsValidDirectory recursively, you need to move the call up to the calling method. Try changing the while block to this:

            while (true)
            {
                if (IsValidDirectory(inputDirectory))
                {
                    break;
                }
    
                Console.WriteLine($"\n\nCheck the directory path and enter it again: ");
                inputDirectory = Console.ReadLine();
            }
    

    and remove the first two lines of your catch block, leaving just:

            catch (Exception e)
            {
                validDirectory = false;
            }