I am writing a simple text editor and currently I am having trouble with the open function. I can successfully read in text from a file, however the trouble I am having is importing it into a text box. Also, I am aware there are questions like this that have already been asked, however I cannot get a working solution from any of them (trust me, I have been trying this for hours). So this is my current open function:
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog openDialog = new OpenFileDialog();
openDialog.Filter = ".TXT File|*.txt|.BAT File|*.bat|All Files|*.*";
openDialog.Title = "Open file";
openDialog.ShowDialog();
if (openDialog.FileName != "")
{
path = openDialog.FileName;
try
{
string[] lines = File.ReadAllLines(path);
//all text from file is now stored in the array "lines"
//put it into text box
for (int i = 0; i < lines.Length; i++)
{
mainTextEntry.AppendText(lines[i]);
}
}
catch (Exception ex)
{
MessageBox.Show("Error while opening file. Original error:\n\n" + ex);
}
}
}
Allow me to point out a few things from that piece of code:
- My text box is called mainTextEntry.
- My openFileDialog is called openDialog.
- Lines is an array, and contains the read in text.
- You can ignore the catch at the bottom, that is just to prevent crashes.
Ok, so that code above gives the following output:
hellotherehow are you?
As you guessed, the file I am reading in has some line breaks in it:
hello
there
how are you?
Of course that is what I want to be printed in mainTextEntry.Text. How would I go about doing this?
EDIT: full source can be found here: MainWin.cs (if you're paranoid click here)