I'm trying to read and write from a txt file using C#. At the moment, I'm writing a program that reads the names in a list, shows them to the user, asks for another name, and then adds that one to the list. The reading is fine, but there's some problems with the writing.
The code compiles fine using CSC, and it executes fine, but after I type the name to add and hit enter, I get a window popping up saying
FileIO.exe has encountered a problem and needs to close.
Any idea what the problem is?
using System;
using System.IO;
public class Hello1
{
public static void Main()
{
int lines = File.ReadAllLines("Name.txt").Length;
string[] stringArray = new string[lines + 1];
StreamReader reader = new StreamReader("Name.txt");
for(int i = 1;i <=lines;i++){
stringArray[i-1] = reader.ReadLine();
}
for (int i = 1;i <=stringArray.Length;i++){
Console.WriteLine(stringArray[i-1]);
}
Console.WriteLine("Please enter a name to add to the list.");
stringArray[lines] = Console.ReadLine();
using (System.IO.StreamWriter writer = new System.IO.StreamWriter("Name.txt", true)){
writer.WriteLine(stringArray[lines]);
}
}
}