Allow players to choose the filename for LoadAllowedWords

From TRCCompSci - AQA Computer Science
Revision as of 13:50, 20 November 2017 by Admin (talk | contribs) (Created page with "The LoadAllowedWords method currently looks like this: <syntaxhighlight lang=c#> private static void LoadAllowedWords(ref List<string> AllowedWords) {...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
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.