C# SaveFileDialog Clicking cancel throws exception -


i have looked around @ possible different ways around issue, haven't found has fixed yet.

everything works normal, savefiledialog box pops , and can click save no problem, if click cancel throws exception.

my code below:

private void createnewfile_click(object sender, routedeventargs e) {     microsoft.win32.savefiledialog savefiledialog1 = new microsoft.win32.savefiledialog();     savefiledialog1.filename = "new note"; //default file name     savefiledialog1.defaultext = ".txt"; //default file extension     savefiledialog1.filter = "text files (.txt)|*.txt"; //filter files extension     savefiledialog1.showdialog(); //bring dialog box      if(savefiledialog1.filename != "")     {         using (streamwriter sw = new streamwriter(savefiledialog1.openfile()))         {             sw.write(textresult.text);         }     }  } 

the line throws error on one:

 using (streamwriter sw = new streamwriter(savefiledialog1.openfile())) 

this line says textresult textbox reading text save txt file

sw.write(textresult.text); 

the exception throwing is

"an unhandled exception of type 'system.argumentexception' occured in mscorlib.dll"  "additional information: absolute path information required" 

you need validate user clicked "save" before trying use streamwriter. also, condition:

if(savefiledialog1.filename != "") 

will true set filename property couple of lines above it.

instead change this:

var result = savefiledialog1.showdialog();  if(result.hasvalue && result.value) 

if user clicks "save" return true, if user clicks "cancel" return false , if user closes box, result not have value.

more information: https://msdn.microsoft.com/en-us/library/dd491101(v=vs.95).aspx


Comments

Popular posts from this blog

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.Error occurred in starting fork -

windows - Debug iNetMgr.exe unhandle exception System.Management.Automation.CmdletInvocationException -