I'm trying to create a save button with the SaveFileDialog in C# with UWP and XAML.
I tried to import Microsoft.Win32
like this post said, but it's not working. The SaveFileDialog()
function tells me:
Error CS0234 The type or namespace name 'SaveFileDialog' does not exist in the namespace 'Microsoft.Win32' (are you missing an assembly reference?)
This is my code:
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = "Document";
dlg.DefaultExt = ".txt";
dlg.Filter = "Text documents (.txt)|*.txt";
How can I fix this?
Instead of following really old advice that was provided at a time when UWP was in preview, you should work your way through the current MS Docs articles that have great simple examples for many common application paradigms.
As a general rule, if you are starting out to develop a new application today, and you have chosen UWP, then you should try to avoid bringing in direct references to the Win32 or the old .Net runtimes. While you can make it work, the backward compatibility is designed to support developers moving legacy code over to .Net Core, for many controls there will already be a native Xaml or WinUI implementation.
Have a look at using the FileSavePicker to
// Create the dialog, this block is equivalent to OPs original code.
var savePicker = new Windows.Storage.Pickers.FileSavePicker();
savePicker.SuggestedStartLocation =
Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary;
// Dropdown of file types the user can save the file as
savePicker.FileTypeChoices.Add("Plain Text", new List<string>() { ".txt" });
// Default file name if the user does not type one in or select a file to replace
savePicker.SuggestedFileName = "Document";
// Show the dialog for the user to specify the target file
// The dialog will return a reference to the file if they click on "save"
// If the user cancels the dialog, null will be returned
Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync();
if (file != null)
{
// Prevent updates to the remote version of the file until
// we finish making changes and call CompleteUpdatesAsync.
Windows.Storage.CachedFileManager.DeferUpdates(file);
// write to file
await Windows.Storage.FileIO.WriteTextAsync(file, file.Name);
// Let Windows know that we're finished changing the file so
// the other app can update the remote version of the file.
// Completing updates may require Windows to ask for user input.
Windows.Storage.Provider.FileUpdateStatus status =
await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(file);
if (status == Windows.Storage.Provider.FileUpdateStatus.Complete)
{
System.Diagnostics.Debug.WriteLine("File " + file.Name + " was saved.");
}
else
{
System.Diagnostics.Debug.WriteLine("File " + file.Name + " couldn't be saved.");
}
}
else
{
System.Diagnostics.Debug.WriteLine("User cancelled the save dialog.");
}
If you're just starting out in UWP, make sure you get the following applications and projects: