Point 1 is your solution, really.
You have to keep a Filename
string variable that holds the filename of the current document. If you create a new document, Filename
is null
. Then if you click Save
or Save As...
and the user doesn't cancel the dialog, you store the resulting FileDialog.FileName
in your Filename
variable and then write the file contents.
Now if the user clicks Save
again, you check whether Filename
has a value, and if so, do not present the SaveFileDialog
but simply write to the file again.
Your code will then look something like this:
private String _filename;
void saveToolStripMenuItem_Click()
{
if (String.IsNullOrEmpty(_filename))
{
if (ShowSaveDialog() != DialogResult.OK)
{
return;
}
}
SaveCurrentFile();
}
void saveAsToolStripMenuItem_Click()
{
if (ShowSaveDialog() != DialogResult.OK)
{
return;
}
SaveCurrentFile();
}
DialogResult ShowSaveDialog()
{
var dialog = new SaveFileDialog();
// set your path, filter, title, whatever
var result = dialog.ShowDialog();
if (result == DialogResult.OK)
{
_filename = result.FileName;
}
return result;
}
void SaveCurrentFile()
{
using (var writer = new StreamWriter(_filename))
{
// write your file
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…