我在c#中制作记事本。这是文件的保存部分。但问题是,如果我修改文本并再次保存,它会要求保存一个新文件,而不是保存在原始文件中。
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
saveFileDialog1.Title = "Save file";
saveFileDialog1.FileName = tabControl1.SelectedTab.Text;
saveFileDialog1.Filter = "TEXT|*.txt|DOC|*.doc|DOCX|*.docx|RICH TEXT FILE|*.rtf|ALL FILES|*.*";
saveFileDialog1.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (saveFileDialog1.ShowDialog() == DialogResult.OK && saveFileDialog1.FileName != "")
{
richTextBox1.SaveFile(saveFileDialog1.FileName, RichTextBoxStreamType.RichText);
}
}
答案 0 :(得分:3)
在您的班级中使用具有上次保存文件值的私有字段
var currentFileName = "";
.....
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
saveFileDialog1.Title = "Save file";
saveFileDialog1.FileName = tabControl1.SelectedTab.Text;
saveFileDialog1.Filter = "TEXT|*.txt|DOC|*.doc|DOCX|*.docx|RICH TEXT FILE|*.rtf|ALL FILES|*.*";
saveFileDialog1.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
bool save = true;
if (string.IsNullOrEmpty(currentFileName))
{
var result = saveFileDialog1.ShowDialog();
if (result == DialogResult.OK && saveFileDialog1.FileName != "")
{
currentFileName = saveFileDialog1.FileName;
}
else
{
save = false;
}
}
if (save)
richTextBox1.SaveFile(currentFileName, RichTextBoxStreamType.RichText);
}
答案 1 :(得分:1)
如果您继续显示保存文件对话框,那么这就是您所获得的。 (saveFileDialog1.ShowDialog())
最好是:
tabControl1.SelectedTab.Text
)答案 2 :(得分:0)
为SaveFileDialog
设置.OverWritePrompt为falsehttp://msdn.microsoft.com/en-us/library/system.windows.forms.savefiledialog.overwriteprompt.aspx