3

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?

Chris Schaller
  • 13,704
  • 3
  • 43
  • 81
altude
  • 41
  • 6
  • 2
    Please add source code so we can see what the problem is. – BenceL Feb 14 '21 at 00:06
  • Oh, I'm so sorry! I just edited it! – altude Feb 14 '21 at 01:14
  • Why do you want to use the Win32 SaveFileDialog? – Chris Schaller Feb 14 '21 at 01:15
  • I didn't know what else to use, just following [this stackoverflow post](https://stackoverflow.com/q/5622854/14422320) and [this microsoft docs page](https://learn.microsoft.com/en-us/dotnet/api/microsoft.win32.savefiledialog?view=net-5.0) – altude Feb 14 '21 at 01:18
  • 1
    Its important that you follow the correct branch of MS Docs that matches the platform and framework you are developing in, 9 years ago UWP was a very different beast, for the current implementation of UWP, look also for WinUI 2+ references. Also 9 years ago SO was about getting it done, no matter what the cost, just because someone found an answer, it doesn't mean they asked the right question, or that you should do what they did. Also they were asking about WPF, so not related to you at all really. – Chris Schaller Feb 14 '21 at 01:49

3 Answers3

4

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:

  • XAML Controls Gallery
    This is your One-Stop shop for all the controls you get OOTB, start here!
  • Windows App Studio UWP Samples
    allows you to see and adjust the components of the Windows App Studio UWP Controls and Data Sources libraries. With this app, you can browse through the different controls, edit the attributes to see changes in real time, and even copy the XAML, C#, and JSON code. The purpose of the app is to highlight what’s in the Windows App Studio Libraries.
  • Windows Community Toolkit Sample App
    This is a link to to compiled sample app, this is a collection of new, and sometimes experimental controls that you can use in your UWP application.
  • Get Windows App Samples
    This is a growing library of GitHub repos that demonstrate how to make UWP work for you.
Chris Schaller
  • 13,704
  • 3
  • 43
  • 81
0

Hi You need to Add Refrence Windows.Forms from soultion Explorer Right Click on Refrences in Solution Explorer and Click Add Refrence And add System.Windows.Forms To your Project When You Added This You Can Add System.Windows.Forms to Your Name Spaces

using System.Windows.Forms;

after this you can Use SaveFileDialog

I Using This Way My Code :

 SaveFileDialog save = new SaveFileDialog();
            Nullable<bool> result = save.ShowDialog();
            if (result==true)
            {
              //Your Code here 
          
            }

My NameSpaces Code I Using In My WPF Project :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Net;
using System.Net.NetworkInformation;
using System.Text.RegularExpressions;
using System.IO;
using Microsoft.Win32;
using System.Windows.Forms;
using System.Threading;
Ali Rezaie
  • 31
  • 4
  • Adding `System.Windows.Forms;` gives me a couple errors: 2 of them being that the "`Forms`" does not exist in the namespace `Windows.Forms`, the other one being that I didn't use it. When I try `System.Windows.Forms.SaveFileDialog`, I get the same error as above. – altude Feb 14 '21 at 01:10
  • Add New Windows Forms from Project Tab And Retry Using Save File Dialog If Code Working Successfully Without ErrorrsYou Can Delete Useless Form1 From Your WPF Project – Ali Rezaie Feb 14 '21 at 16:10
0

Based on the document of SaveFileDialog Class, it mentions that the API applies to .NET Core 3.0 and 3.1. But UWP only supports .NET Core 2.0 currently. That's why you meet this unexpected. The link you posted is a WPF question and it might not be suitable for UWP.

@Chris Schaller solution is correct and you could make a try with FileSavePicker.

Roy Li - MSFT
  • 8,043
  • 1
  • 7
  • 13