How do I show a Save As dialog in WPF?

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.


Solution 1:

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

Solution 2:

SaveFileDialog is in the Microsoft.Win32 namespace - might save you the 10 minutes it took me to figure this out.

Solution 3:

Here is some sample code:

string fileText = "Your output text";

SaveFileDialog dialog = new SaveFileDialog()
{
    Filter = "Text Files(*.txt)|*.txt|All(*.*)|*"
};

if (dialog.ShowDialog() == true)
{
     File.WriteAllText(dialog.FileName, fileText);
}

Solution 4:

Use the SaveFileDialog class.

Solution 5:

You just need to create a SaveFileDialog, and call its ShowDialog method.