正在关闭saveFileDialog
本文关键字:saveFileDialog | 更新日期: 2023-09-27 18:26:42
我在关闭saveFileDialog时遇到问题。当我单击"取消"时,窗口再次出现。这是我的代码:
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);
if (saveFileDialog1.ShowDialog()==DialogResult.Cancel)
{
richTextBox1.Text = "CANCEL";
issaved = false;
}
else
{
issaved = true;
SaveFile.WriteLine(richTextBox1.Text);
}
SaveFile.Close();
}
您调用saveFileDialog1.ShowDialog()
两次,一次显示它,一次获取结果。你只需要打一次电话。去掉这样一行:saveFileDialog1.ShowDialog();
本身,你已经在if
条件中这样做了。
编辑:您还需要将所有FileStream
操作移动到else块中,以便在删除该行后使其正常工作。这是我编辑过的版本:
private void SaveAsItem_Click(object sender, EventArgs e)
{
saveFileDialog1.FileName = "untitled";
saveFileDialog1.Filter = "Text (*.txt)|*.txt";
if (saveFileDialog1.ShowDialog()==DialogResult.Cancel)
{
richTextBox1.Text = "CANCEL";
issaved = false;
}
else
{
System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(saveFileDialog1.FileName);
issaved = true;
SaveFile.WriteLine(richTextBox1.Text);
SaveFile.Close();
}
}
你也可以完全跳过FileStream
,只做一个File.WriteAlltext(saveFileDialog1.FileName, richTextBox1.Text)
。