Allow players to choose the filename for LoadAllowedWords

From TRCCompSci - AQA Computer Science
Jump to: navigation, search

The LoadAllowedWords method currently looks like this:

        private static void LoadAllowedWords(ref List<string> AllowedWords)
        {
            try
            {
                StreamReader FileReader = new StreamReader("aqawords.txt");
                while (!FileReader.EndOfStream)
                {
                    AllowedWords.Add(FileReader.ReadLine().Trim().ToUpper());
                }
                FileReader.Close();
            }
            catch (Exception)
            {
                AllowedWords.Clear();
            }
        }

We can add additional code to allow the user to enter the name of the file to load:

        private static void LoadAllowedWords(ref List<string> AllowedWords)
        {
            string filename = "";
            do
            {
                Console.WriteLine("Please enter a filename: ");
                filename = Console.ReadLine();
            }
            while (filename=="");

            try
            {
                StreamReader FileReader = new StreamReader("aqawords.txt");
                while (!FileReader.EndOfStream)
                {
                    AllowedWords.Add(FileReader.ReadLine().Trim().ToUpper());
                }
                FileReader.Close();
            }
            catch (Exception)
            {
                AllowedWords.Clear();
            }
        }

Any error, such as the file not existing or any other error will be caught by the catch.