简体   繁体   English

C#SaveFileDialog单击取消引发异常

[英]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. 一切正常,弹出SaveFileDialog框,您可以单击“保存没有问题”,如果单击“取消”,则会引发异常。

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 这行显示textResult是要从中读取文本以保存到TXT文件的textbox

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. 您需要先验证用户是否实际单击了“保存”,然后才能尝试使用StreamWriter。 Also, your condition: 另外,您的条件:

if(saveFileDialog1.FileName != "")

will always be true as you set the FileName property just a couple of lines above it. 当您将FileName属性设置为仅在其上方两行时,它将始终为true。

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. 如果用户单击“保存”,它将返回true;如果用户单击“取消”,它将返回false;如果用户关闭该框,则结果将没有值。

More information: https://msdn.microsoft.com/en-us/library/dd491101(v=vs.95).aspx 详细信息: https : //msdn.microsoft.com/zh-cn/library/dd491101(v=vs.95).aspx

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

if(saveFileDialog1.DialogResult == DialogResult.OK ) 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. 在这种情况下,如果单击“保存”,则单击“取消”,它将继续进行流写入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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