簡體   English   中英

C#SaveFileDialog單擊取消引發異常

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM