Reputation: 350
I have looked everywhere and can't find the thing I am looking for. What I want is code for the saveToolStripMenuItem_Click event handler on the "Save" menu (NOT "Save As...") and have my app check to see if:
The current file has already been saved, therefore already has a filename.
The current file has been modified since being opened.
Overwrite (or append, as needed) the existing file without bringing up the "Save As" dialog.
Brings up the "Save As..." menu if the file does not already exist.
My "Save As..." menu already works properly. Everything I have found tells me how to create a "Save As.." dialog, which I already know. Every sample program I have downloaded does not have this functionality.
Any help would be appreciated.
Upvotes: 0
Views: 3450
Reputation: 151586
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
}
}
Upvotes: 1
Reputation: 11191
You can achieve the requirements mentioned as points by writing custom using
System.IO.FileOptions and System.IO.File methods
http://msdn.microsoft.com/en-us/library/system.io.file_methods
Upvotes: 0