Search code examples
c#openfiledialog

openfile dialog cancel crash


I am making a basic word processor in c# for training. Now I am making the open file part of it. I can open a text file without issue. But when I open the open file dialog and then cancel it, it crashes :/

private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
    openFileDialog1.ShowDialog();
    var OpenFile = new System.IO.StreamReader(openFileDialog1.FileName);
    getRichTextBox().Text = OpenFile.ReadToEnd();
}

I know it is because the streamreader has nothing to read but I am not sure how to solve this.

thanks in advance!

Edit: Thank you! it worked perfectly :)


Solution

  • You need to check the result of the dialog:

    private void openToolStripMenuItem_Click(object sender, EventArgs e)
    {
        if (openFileDialog1.ShowDialog() == DialogResult.OK) {
            using (var openFile = new StreamReader(openFileDialog1.FileName)) {
                getRichTextBox().Text = OpenFile.ReadToEnd();
            }
        }
    }
    

    I've also added a using statement to ensure that your file is closed when you're done reading it.

    You can simplify the code even further by simply using File.ReadAllText instead of messing around with StreamReader.

    getRichTextBox().Text = File.ReadAllText(openFileDialog1.FileName);
    

    (Thanks @keyboardP)