Allow players to save the new AllowedWords back into aqawords.txt
The first thing you should do is find the method which loads the AllowedWords:
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 are going to follow this structure but change everything to write instead of reading the files. Firstly create a new method:
private static void SaveAllowedWords(ref List<string> AllowedWords)
{
}
Now to setup the file writer:
private static void SaveAllowedWords(ref List<string> AllowedWords)
{
StreamWriter FileWriter = new StreamWriter("aqawords.txt");
FileReader.Close();
}
Now we need a loop to cycle through each allowed word, and write it to the file:
private static void SaveAllowedWords(ref List<string> AllowedWords)
{
StreamWriter FileWriter = new StreamWriter("aqawords.txt");
foreach (string word in AllowedWords)
{
FileWriter.WriteLine(word);
}
FileWriter.Close();
}
To keep the file in order we could also sort the list of allowed words before we write it:
private static void SaveAllowedWords(ref List<string> AllowedWords)
{
StreamWriter FileWriter = new StreamWriter("aqawords.txt");
AllowedWords.Sort();
foreach (string word in AllowedWords)
{
FileWriter.WriteLine(word);
}
FileWriter.Close();
}
You might want to specify a file name, so you could use readline to get the file name:
private static void SaveAllowedWords(ref List<string> AllowedWords)
{
string filename = "";
do
{
Console.WriteLine("Please enter a filename: ");
filename = Console.ReadLine();
}
while (filename == "");
StreamWriter FileWriter = new StreamWriter(filename);
AllowedWords.Sort();
foreach (string word in AllowedWords)
{
FileWriter.WriteLine(word);
}
FileWriter.Close();
}