[英]C# SaveFileDialog Clicking cancel throws exception
我已经研究了解决此问题的不同方法,但是还没有找到解决此问题的方法。
一切正常,弹出SaveFileDialog
框,您可以单击“保存没有问题”,如果单击“取消”,则会引发异常。
我的代码如下:
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);
}
}
}
引发错误的行是这一行:
using (StreamWriter sw = new StreamWriter(saveFileDialog1.OpenFile()))
这行显示textResult
是要从中读取文本以保存到TXT文件的textbox
sw.Write(textResult.Text);
它抛出的异常是
"An unhandled exception of type 'System.ArgumentException' occured in mscorlib.dll"
"Additional information: Absolute path information is required"
您需要先验证用户是否实际单击了“保存”,然后才能尝试使用StreamWriter。 另外,您的条件:
if(saveFileDialog1.FileName != "")
当您将FileName属性设置为仅在其上方两行时,它将始终为true。
改为更改为:
var result = saveFileDialog1.ShowDialog();
if(result.HasValue && result.Value)
如果用户单击“保存”,它将返回true;如果用户单击“取消”,它将返回false;如果用户关闭该框,则结果将没有值。
详细信息: https : //msdn.microsoft.com/zh-cn/library/dd491101(v=vs.95).aspx
代替if(saveFileDialog1.FileName != "")
试试
if(saveFileDialog1.DialogResult == DialogResult.OK
)
在这种情况下,如果单击“保存”,则单击“取消”,它将继续进行流写入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.