简体   繁体   中英

Bypassing save dialog box in WPF application

I am trying to bypass the save dialog box when using the SaveFileDialog class. I want to be able to write to a document without having to prompt a user to decide if they want to save or not, the file should automatically save when they click a button.

 SaveFileDialog saveFileDialog1 = new SaveFileDialog();

 saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"  ;
 saveFileDialog1.RestoreDirectory = true ;
 saveFileDialog1.InitialDirectory = @"C:\";
 if(saveFileDialog1.ShowDialog() == DialogResult.OK)
 {
     // Code to write the stream goes here.
 }

I have tried removing the if statement as well as using...

saveFileDialog1.CreatePRompt = false;

Nothing seems to work... Any ideas?

I think you want to bypass the overwrite prompt dialog.

In this case you can use

saveFileDialog1.OverwritePrompt = false;

Otherwise, you don't need a SaveFileDialog and you can save your stream without using it.

I found my answer. The question I asked was actually two it seems. The first was how to bypass SaveFileDialog, I wanted to use saveFileDialog because it can remember the last folder it accessed and opens to that folder when performing a read/save. That being said I implemented this...

Directory = System.AppDomain.CurrentDomain.BaseDirectory;

This will set Directory to the location of my executable.

Next I got rid of SaveFileDialog and just wrote to a file without ever prompting the user.

Thanks for all the pointers and ideas!

The end result ended up...

Directory = System.AppDomain.CurrentDomain.BaseDirectory;
using(System.IO.StreamWriter file = new System.IO.StreamWriter(Directory, false))
{
    // File contents
}

Works perfectly for what I need it for.

If you want to save but you need the user to pick a filename, I would use this:

SaveFileDialog saveFileDialog1 = new SaveFileDialog();
//setup properties of Dialog
bool filenamepicked = false;
while (!filenamepicked)
{
    if (saveFileDialog1.ShowDialog() == DialogResult.OK)
    {
        //Save file
        filenamepicked = true;
    }
    else
    {
        MessageBox.Show("You have to use a file name.");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM