LoadAllowedWords

From TRCCompSci - AQA Computer Science
Revision as of 12:49, 14 November 2017 by Admin (talk | contribs)
Jump to: navigation, search

<syntaxhighlight lang=csharp>

       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();
           }
       }

<syntaxhighlight>

This method attempts to read the aqawords.txt file and convert each line into a viable word. Note that because the method is wrapped in a try catch statement with catch type associated with the root class Exception, any exception thrown at any point can put a cog in the works. For a common example if the file doesn't exist in the path we've specified (I.E. the local directory the program is in, then a FileNotFoundException will be thrown, caught and handled). However for a less common exception, if the given file contains characters not associated with the default encoding standard of the filestream then a new exception will be thrown because the reader can't interpret the file. In both these cases the entire AllowedWords list is cleared and therefore so long as one word cannot be read, the entire file will be considered invalid (for better or worse that's how it is).

Within the try block, the method tries to open a filestream, specified for reading and then continually reads each line until the end of the stream (adding them to the list along the way) before finally closing the stream and ending; a whole host of problems can occur before this step, but for now it works so don't try to modify it too much.