你應該嘗試添加從富文本從加載的文件名或FileInfo的。如果文件尚未保存,請提示保存文件。否則,保存到緩存的文件信息。
partial class YourForm : Form
{
string filePath;
private void SaveMyFile_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(filePath))
{
SaveFileDialog saveFile1 = new SaveFileDialog();
saveFile1.DefaultExt = "*.rtf";
saveFile1.Filter = "RTF Files|*.rtf";
if (saveFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK &&
saveFile1.FileName.Length > 0)
{
filePath = saveFile1.FileName;
}
else return;
}
try
{
richTextBox1.SaveFile(filePath, RichTextBoxStreamType.PlainText);
}
catch (Exception ee)
{
// Put exception handling code here
}
}
}
按照下面的評論,如果你想要一個另存爲按鈕,你可以嘗試以下方法:
partial class YourForm : Form
{
Button saveFileAsButton; // Add this using the Forms Designer
private void saveFileAsButton_Click(object sender, EventArgs e)
{
SaveFileDialog saveFile1 = new SaveFileDialog();
saveFile1.DefaultExt = "*.rtf";
saveFile1.Filter = "RTF Files|*.rtf";
if (saveFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK &&
saveFile1.FileName.Length > 0)
{
try
{
richTextBox1.SaveFile(saveFile1.FileName, RichTextBoxStreamType.PlainText);
filePath = saveFile1.FileName;
}
catch (Exception ee)
{
// Put exception handling code here (e.g. error saying file cannot be saved)
}
}
}
}
注filePath
的設置是如何在try塊。如果保存失敗,則不希望丟失原始文件路徑。
如果您的表格有MenuStrip
,我建議將保存功能移到菜單中。
(順便說一句,在你的過濾器RTF類型名稱將是爲「Rich Text Document
」更好。)
請出示你在那裏打開該文件中的代碼... – Yahia 2012-01-31 17:07:11