How do I show a Save As dialog in WPF?

Unknown Coder picture Unknown Coder · Apr 11, 2011 · Viewed 81.1k times · Source

I have a requirement in WPF/C# to click on a button, gather some data and then put it in a text file that the user can download to their machine. I can get the first half of this, but how do you prompt a user with a "Save As" dialog box? The file itself will be a simple text file.

Answer

Aaron McIver picture Aaron McIver · Apr 11, 2011

Both answers thus far link to the Silverlight SaveFileDialogclass; the WPF variant is quite a bit different and differing namespace.

Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = "Document"; // Default file name
dlg.DefaultExt = ".text"; // Default file extension
dlg.Filter = "Text documents (.txt)|*.txt"; // Filter files by extension

// Show save file dialog box
Nullable<bool> result = dlg.ShowDialog();

// Process save file dialog box results
if (result == true)
{
    // Save document
    string filename = dlg.FileName;
}