清除richtextbox并覆盖以前的条目
本文关键字:richtextbox 覆盖 清除 | 更新日期: 2023-09-27 18:22:04
我有一个richtextbox,它将覆盖以前已经保存的文件。
如果我需要启动一个新文件,然后将其另存为新文件,它只会覆盖保存的第一个文件。
如何做到这一点?
String fileLocation;
private void SaveMyFile_Click(object sender, EventArgs e)
{
var performSave = true;
if (String.IsNullOrEmpty(fileLocation))
{
performSave = SetFileLocation();
}
if (performSave)
richTextBox1.SaveFile(fileLocation, RichTextBoxStreamType.PlainText);
}
private bool SetFileLocation()
{
SaveFileDialog saveFile1 = new SaveFileDialog();
saveFile1.DefaultExt = "*.txt";
saveFile1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*|RTF Files|*.rtf";
if (saveFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK &&
saveFile1.FileName.Length > 0)
{
fileLocation = saveFile1.FileName;
return true;
}
return false;
}
第一次保存(SetLocation)后的fileLocation变量既不为null也不为空,这就是为什么当您再次保存(单击SaveMyFile按钮)时,它不会进入SetFileLocation方法,而只执行SaveFile
当您"启动一个新文件"时,只需将fileLocation
设置为null,就可以再次显示SaveFileDialog
,从而允许您输入一个新的文件位置。下面的代码是关键的一点:
if (String.IsNullOrEmpty(fileLocation))
{
performSave = SetFileLocation();
}
除非fileLocation
为null或为空字符串,否则不会调用SetFileLocation()
方法。