I have a method that reads a text file and writes the contents to an array list. The array list is declared globally with no elements. This method works perfectly.
private void LoadArrayList()
{
try
{
string actor;
TextReader tr;
tr = File.OpenText("actors.txt");
while ((actor = tr.ReadLine()) != null)
{
ActorArrayList.Add(actor);
}
tr.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error loading file!");
}
}
I now need to create a method that reads the array list and writes the contents back to the text file, replacing what is currently in the text file. This method results in a blank text file. Any idea's what I am missing/doing wrong?
private void WriteArrayList()
{
TextWriter tw;
try
{
tw = File.CreateText("actors.txt");
foreach (object o in ActorArrayList)
tw.WriteLine(o.ToString());
}
catch (Exception ex)
{
MessageBox.Show("Error saving file!");
}
}
NOTE: I know people don't seem to like array lists or TextReader or TextWriter, but the course I am doing covers them so I am required to use them.
ArrayList, you usually only use that for backwards compatibility, it is generally preferable to useList<T>, in this case aList<string>.usingblocks when you handle classes implementingIDisposable. If you have a Visual Studio that supports it, turn on static code analysis so you will get a warning when you forget it.tw.Close();at the end of your method.