我的程序中有一个 SaveFileDialog。问题是当我在对话框上单击“取消”时,会打开另一个 SaveFileDialog。但是当我在第二个 SaveFileDialog 上单击取消时,第三个不会出现,所以它不是循环或类似的东西。我看不出是什么导致我的 SaveFileDialog 表现得如此奇怪。显然我需要解决这个问题,以便如果用户在第一个 SaveFileDialog 上单击取消,它会将它们返回到表单。
在我的程序中保存的代码如下:
private void SaveFile()
{
if (filepath == null)
{
SaveFileAs();
}
else
{
StreamWriter sw = new StreamWriter(filepath);
try
{
sw.WriteLine(richTextBoxPrintCtrl1.Rtf);
richTextBoxPrintCtrl1.Modified = false;
sw.Close();
lastsave.Text = "Last Saved: " + DateTime.Now.ToString();
}
catch (Exception exc)
{
MessageBox.Show("Failed to save file. \n \n" + exc.Message);
}
finally
{
if (sw != null) sw.Close();
}
并将文件另存为
private void SaveFileAs()
{
SaveFileDialog sfdSaveFile = new SaveFileDialog();//Creates a new instance of the SaveFileDialog
sfdSaveFile.Title = "Save File";//The title of the SaveFileDialog window
sfdSaveFile.FileName = "Untitled";//The default filename in the SaveFileDialog window
sfdSaveFile.Filter = "Rich Text Files (*.rtf)|*.rtf|Text Document (*.txt)|*.txt";//The supported file extensions when saving
if (sfdSaveFile.ShowDialog() == DialogResult.OK)//If the condition is correct, run the lines of code
try//try to run the code
{
filepath = sfdSaveFile.FileName;//get the filepath of the file once it is saved
SaveFile();//Calls the SaveFile object
this.Text = string.Format("{0} - Basic Word Processor", Path.GetFileName(sfdSaveFile.FileName));//Set the form name
lastsave.Text = "Last Saved: " + DateTime.Now.ToString();//Writes the text to the lastsave.Text label, followed by the current date and time
richTextBoxPrintCtrl1.Modified = false;
return;
}
catch (Exception exc)//Catches any errors
{
MessageBox.Show("An error occured whilst saving. " + exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (sfdSaveFile.ShowDialog() == DialogResult.Cancel)
{
return;
}
else if (sfdSaveFile.ShowDialog() == DialogResult.Cancel)//If the condition is true, run the line of code
{
return;
}
如果有人可以帮助我确定为什么会发生这种情况,我将非常感激..
- 编辑 -
我忘了提到,如果用户确实浏览并保存了文件,SaveFileDialog 不会打开另一个 SaveFileDialog。这与取消导致问题的 SaveFileDialog 有关。