c# - openfile dialog cancel crash -


i making basic word processor in c# training. making open file part of it. can open text file without issue. when open open file dialog , cancel 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 because streamreader has nothing read not sure how solve this.

thanks in advance!

edit: thank you! worked :)

you need check result of 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 added using statement ensure file closed when you're done reading it.

you can simplify code further using file.readalltext instead of messing around streamreader.

getrichtextbox().text = file.readalltext(openfiledialog1.filename); 

(thanks @keyboardp)


Comments

Popular posts from this blog

ios - UICollectionView Self Sizing Cells with Auto Layout -

node.js - ldapjs - write after end error -

DOM Manipulation in Wordpress (and elsewhere) using php -