2012-03-05 94 views
1

我想寫記事本,我怎麼知道用戶點擊'取消'?我的代碼無法正常工作:用C保存文本文件#

private void SaveAsItem_Click(object sender, EventArgs e) 
{ 
    saveFileDialog1.FileName = "untitled"; 
    saveFileDialog1.Filter = "Text (*.txt)|*.txt"; 
    saveFileDialog1.ShowDialog(); 
    System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(saveFileDialog1.FileName); 
    SaveFile.WriteLine(richTextBox1.Text); 
    SaveFile.Close(); 
    if (DialogResult == DialogResult.Cancel) 
    { 
     richTextBox1.Text = "CANCEL"; 
     issaved = false; 
    } 
    else 
    { 
     issaved = true; 
    } 
} 

回答

4

你檢查DialogResult財產您的主要形式,但它是要檢查孩子的形式。所以......

var dr = saveFileDialog1.ShowDialog(); 
if(dr == DialogResult.OK) 
{ 
    using(var SaveFile = new StreamWriter(saveFileDialog1.FileName)) 
    { 
     SaveFile.WriteLine(richTextBox1.Text); 
     issaved = true; 
    } 
} 
else // cancel (or something else) 
{ 
    richTextBox1.Text = "CANCEL"; 
    issaved = false;  
} 

此外,你應該在using塊如我上面做包裝你StreamWriter。如果發生異常,您的代碼將無法關閉文件。 A using區塊是try/finally區塊的語法糖,該區塊在finally部分中調用Dispose()(它又調用Close())。

0

在檢查對話框的結果之前,您正在創建文件。將SaveFile變量位移入「issaved = true」塊。

[編輯]和其他人說,檢查結果對話框正確

1
DialogResult res = saveFileDialog1.ShowDialog(); 
if (res == DialogResult.Cancel) { 
    // user cancelled 
} 
else { 
    // Write file to disk using the filename chosen by user 
}