質問

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 :)

役に立ちましたか?

解決

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)

他のヒント

if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
    var OpenFile = new System.IO.StreamReader(openFileDialog1.FileName);
    getRichTextBox().Text = OpenFile.ReadToEnd();
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top