Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
277 views
in Technique[技术] by (71.8m points)

c# - Saving file without dialog

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:

  1. The current file has already been saved, therefore already has a filename.

  2. The current file has been modified since being opened.

  3. Overwrite (or append, as needed) the existing file without bringing up the "Save As" dialog.

  4. 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...