简体   繁体   中英

C# SaveFileDialog Clicking cancel throws exception

I have looked around at possible different ways around this issue, but haven't found something that has fixed this yet.

Everything works as normal, the SaveFileDialog box pops up and and you can click save no problem, if you click cancel it throws an exception.

My code is 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 by extension
    saveFileDialog1.ShowDialog(); //bring up the Dialog box

    if(saveFileDialog1.FileName != "")
    {
        using (StreamWriter sw = new StreamWriter(saveFileDialog1.OpenFile()))
        {
            sw.Write(textResult.Text);
        }
    }

}

The Line it throws the error on is this one:

 using (StreamWriter sw = new StreamWriter(saveFileDialog1.OpenFile()))

This line where it says textResult is the textbox it is reading the text from to save to a TXT file

sw.Write(textResult.Text);

The exception it is throwing is

"An unhandled exception of type 'System.ArgumentException' occured in mscorlib.dll"

"Additional information: Absolute path information is required"

You need to validate that the user actually clicked "Save" before trying to use the StreamWriter. Also, your condition:

if(saveFileDialog1.FileName != "")

will always be true as you set the FileName property just a couple of lines above it.

Instead change to this:

var result = saveFileDialog1.ShowDialog();

if(result.HasValue && result.Value)

If the user clicks "Save" it will return true, if the user clicks "Cancel" it will return false and if the user closes the box, result will not have a value.

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

instead of if(saveFileDialog1.FileName != "") try

if(saveFileDialog1.DialogResult == DialogResult.OK )

in this case if you click save it will procceed to streamwriter if you click cancel it will close dialog without farther actions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM