Jaa


FileSavePicker Class

Definition

Represents a file picker that lets the user choose the file name, extension, and storage location for a file.

In a desktop app, before using an instance of this class in a way that displays UI, you'll need to associate the object with its owner's window handle. For more info, and code examples, see Display WinRT UI objects that depend on CoreWindow.

public ref class FileSavePicker sealed
/// [Windows.Foundation.Metadata.Activatable(65536, Windows.Foundation.UniversalApiContract)]
/// [Windows.Foundation.Metadata.ContractVersion(Windows.Foundation.UniversalApiContract, 65536)]
class FileSavePicker final
/// [Windows.Foundation.Metadata.ContractVersion(Windows.Foundation.UniversalApiContract, 65536)]
/// [Windows.Foundation.Metadata.Activatable(65536, "Windows.Foundation.UniversalApiContract")]
class FileSavePicker final
/// [Windows.Foundation.Metadata.ContractVersion(Windows.Foundation.UniversalApiContract, 65536)]
/// [Windows.Foundation.Metadata.Activatable(65536, "Windows.Foundation.UniversalApiContract")]
/// [Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
/// [Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
class FileSavePicker final
[Windows.Foundation.Metadata.Activatable(65536, typeof(Windows.Foundation.UniversalApiContract))]
[Windows.Foundation.Metadata.ContractVersion(typeof(Windows.Foundation.UniversalApiContract), 65536)]
public sealed class FileSavePicker
[Windows.Foundation.Metadata.ContractVersion(typeof(Windows.Foundation.UniversalApiContract), 65536)]
[Windows.Foundation.Metadata.Activatable(65536, "Windows.Foundation.UniversalApiContract")]
public sealed class FileSavePicker
[Windows.Foundation.Metadata.ContractVersion(typeof(Windows.Foundation.UniversalApiContract), 65536)]
[Windows.Foundation.Metadata.Activatable(65536, "Windows.Foundation.UniversalApiContract")]
[Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
[Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
public sealed class FileSavePicker
function FileSavePicker()
Public NotInheritable Class FileSavePicker
Inheritance
Object Platform::Object IInspectable FileSavePicker
Attributes

Windows requirements

Device family
Windows 10 (introduced in 10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (introduced in v1.0)

Examples

The File picker sample is available in C# and C++/WinRT versions. It demonstrates how to check whether the app is snapped, how to set file picker properties, and how to show a file picker so that the user can save a file.

Here's an excerpt from the C# version of the sample app.

if (rootPage.EnsureUnsnapped())
{
    FileSavePicker savePicker = new FileSavePicker();
    savePicker.SuggestedStartLocation = 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 = "New Document";

    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.
        CachedFileManager.DeferUpdates(file);
        // write to file
        await 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.
        FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);
        if (status == FileUpdateStatus.Complete)
        {
            OutputTextBlock.Text = "File " + file.Name + " was saved.";
        }
        else
        {
            OutputTextBlock.Text = "File " + file.Name + " couldn't be saved.";
        }
    }
    else
    {
        OutputTextBlock.Text = "Operation cancelled.";
    }
}

Remarks

Important

You must use the FileTypeChoices property property to specify one or more file types before you call the PickSaveFileAsync method, or the picker will thrown an exception.

To learn how to save files through the file picker, see How to save files through file pickers.

To get started accessing files and folders file picker, see Files, folders, and libraries .

Warning

If you try to show the file picker while your app is snapped, the file picker will not be shown and an exception will be thrown. You can avoid this by making sure your app is not snapped or by unsnapping it before you call the file picker. The following code examples and the File picker sample show you how.

In a desktop app that requires elevation

In a desktop app (which includes WinUI 3 apps), you can use FileSavePicker (and other types from Windows.Storage.Pickers). But if the desktop app requires elevation to run, then you'll need a different approach (that's because these APIs aren't designed to be used in an elevated app). The code snippet below illustrates how you can use the C#/Win32 P/Invoke Source Generator (CsWin32) to call the Win32 picking APIs instead. To learn how to use CsWin32, follow that link for the documentation.

// NativeMethods.txt
CoCreateInstance
FileSaveDialog
IFileSaveDialog
SHCreateItemFromParsingName

// MainWindow.xaml
...
<TextBlock x:Name="OutputTextBlock"/>
...

// MainWindow.xaml.cs
using Microsoft.UI.Xaml;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;

using Windows.Win32;
using Windows.Win32.Foundation;
using Windows.Win32.System.Com;
using Windows.Win32.UI.Shell;
using Windows.Win32.UI.Shell.Common;

namespace FileSavePickerExample
{
    public sealed partial class MainWindow : Window
    {
        public MainWindow()
        {
            this.InitializeComponent();
        }

        private unsafe void myButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // Retrieve the window handle (HWND) of the main WinUI 3 window.
                var hWnd = WinRT.Interop.WindowNative.GetWindowHandle(this);

                int hr = PInvoke.CoCreateInstance<IFileSaveDialog>(
                    typeof(FileSaveDialog).GUID,
                    null,
                    CLSCTX.CLSCTX_INPROC_SERVER,
                    out var fsd);
                if (hr < 0)
                {
                    Marshal.ThrowExceptionForHR(hr);
                }

                // Set file type filters.
                string filter = "Word Documents|*.docx|JPEG Files|*.jpg";

                List<COMDLG_FILTERSPEC> extensions = new List<COMDLG_FILTERSPEC>();

                if (!string.IsNullOrEmpty(filter))
                {
                    string[] tokens = filter.Split('|');
                    if (0 == tokens.Length % 2)
                    {
                        // All even numbered tokens should be labels.
                        // Odd numbered tokens are the associated extensions.
                        for (int i = 1; i < tokens.Length; i += 2)
                        {
                            COMDLG_FILTERSPEC extension;

                            extension.pszSpec = (char*)Marshal.StringToHGlobalUni(tokens[i]);
                            extension.pszName = (char*)Marshal.StringToHGlobalUni(tokens[i - 1]);
                            extensions.Add(extension);
                        }
                    }
                }

                fsd.SetFileTypes(extensions.ToArray());

                // Set the default folder.
                hr = PInvoke.SHCreateItemFromParsingName(
                    Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
                    null,
                    typeof(IShellItem).GUID,
                    out var directoryShellItem);
                if (hr < 0)
                {
                    Marshal.ThrowExceptionForHR(hr);
                }

                fsd.SetFolder((IShellItem)directoryShellItem);
                fsd.SetDefaultFolder((IShellItem)directoryShellItem);

                // Set the default file name.
                fsd.SetFileName($"{DateTime.Now:yyyyMMddHHmm}");

                // Set the default extension.
                fsd.SetDefaultExtension(".docx");

                fsd.Show(new HWND(hWnd));

                fsd.GetResult(out var ppsi);

                PWSTR filename;
                ppsi.GetDisplayName(SIGDN.SIGDN_FILESYSPATH, &filename);

                OutputTextBlock.Text = filename.ToString();
            }
            catch (Exception ex)
            {
                OutputTextBlock.Text = "a problem occured: " + ex.Message;
            }
        }
    }
}

Version history

Windows version SDK version Value added
1903 18362 CreateForUser
1903 18362 User

Constructors

FileSavePicker()

Creates a new instance of a FileSavePicker.

In a desktop app, before using an instance of this class in a way that displays UI, you'll need to associate the object with its owner's window handle. For more info, and code examples, see Display WinRT UI objects that depend on CoreWindow.

Properties

CommitButtonText

Gets or sets the label text of the commit button in the file picker UI.

ContinuationData

Gets a set of values to be populated by the app before a PickSaveFileAndContinue operation that deactivates the app in order to provide context when the app is activated. (Windows Phone 8.x app)

DefaultFileExtension

Important

Do not use this property. Use the FileTypeChoices property instead. The default file extension is set by the first file type in the first file type group in FileTypeChoices.

Gets or sets the default file name extension that the fileSavePicker gives to files to be saved.

EnterpriseId

Gets or sets an ID that specifies the enterprise that owns the file.

FileTypeChoices

Gets the collection of valid file types that the user can choose to assign to a file.

SettingsIdentifier

Gets or sets the settings identifier associated with the current FileSavePicker instance.

SuggestedFileName

Gets or sets the file name that the file save picker suggests to the user.

SuggestedSaveFile

Gets or sets the storageFile that the file picker suggests to the user for saving a file.

SuggestedStartLocation

Gets or sets the location that the file save picker suggests to the user as the location to save a file.

User

Gets info about the user for which the FileSavePicker was created. Use this property for multi-user applications.

Methods

CreateForUser(User)

Creates a FileSavePicker that is scoped to the personal directory of the specified user. Use this method for multi-user applications.

PickSaveFileAndContinue()

Obsolete as of Windows 10; use PickSaveFileAsync instead. Shows the file picker so that the user can save a file, deactivating and the app and reactivating it when the operation is complete. (Windows Phone 8.x app)

PickSaveFileAsync()

Shows the file picker so that the user can save a file and set the file name, extension, and location of the file to be saved. (UWP app)

Applies to

See also