FileSavePicker 類別

定義

代表檔案選擇器,讓使用者選擇檔案的檔案名、副檔名和儲存位置。

在傳統型應用程式中,在以顯示 UI 的方式使用這個類別的實例之前,您必須將物件與其擁有者的視窗控制碼產生關聯。 如需詳細資訊和程式碼範例,請參閱 顯示相依于 CoreWindow 的 WinRT UI 物件

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
繼承
Object Platform::Object IInspectable FileSavePicker
屬性

Windows 需求

裝置系列
Windows 10 (已於 10.0.10240.0 引進)
API contract
Windows.Foundation.UniversalApiContract (已於 v1.0 引進)

範例

檔案 選擇器範例 適用于 C# 和 C++/WinRT 版本。 其示範如何檢查應用程式是否已貼齊、如何設定檔案選擇器屬性,以及如何顯示檔案選擇器,讓使用者可以儲存檔案。

以下是範例應用程式的 C# 版本摘錄。

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

備註

重要

呼叫 PickSaveFileAsync 方法之前,您必須使用 FileTypeChoices 屬性 來指定一或多個檔案類型,否則選擇器會擲回例外狀況。

若要瞭解如何透過檔案選擇器儲存檔案,請參閱 如何透過檔案選擇器儲存檔案

若要開始存取檔案和資料夾檔案選擇器,請參閱 檔案、資料夾和程式庫

警告

如果您嘗試在應用程式貼齊時顯示檔案選擇器,將不會顯示檔案選擇器,而且會擲回例外狀況。 在呼叫檔案選擇器之前,您可以確定您的應用程式未貼齊或取消套用,以避免這種情況。 下列程式碼範例和 檔案選擇器範例 會示範如何。

在需要提高許可權的桌面應用程式中

在包含 WinUI 3 應用程式 () 的桌面應用程式中,您可以使用 FileSavePicker (,以及 Windows.Storage.Pickers) 的其他類型。 但是,如果傳統型應用程式需要提高許可權才能執行,則您需要不同的方法 (,因為這些 API 並非設計成用於提升許可權的應用程式) 。 下列程式碼片段說明如何使用 C#/Win32 P/Invoke 來源產生器 (CsWin32) 來呼叫 Win32 挑選 API。 若要瞭解如何使用 CsWin32,請遵循檔的連結。

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

版本歷程記錄

Windows 版本 SDK 版本 已新增值
1903 18362 CreateForUser
1903 18362 User

建構函式

FileSavePicker()

建立 FileSavePicker的新實例。

在傳統型應用程式中,在以顯示 UI 的方式使用這個類別的實例之前,您必須將物件與其擁有者的視窗控制碼產生關聯。 如需詳細資訊和程式碼範例,請參閱 顯示相依于 CoreWindow 的 WinRT UI 物件

屬性

CommitButtonText

取得或設定檔案選擇器 UI 中認可按鈕的標籤文字。

ContinuationData

取得應用程式在 PickSaveFileAndContinue 作業之前要填入的一組值,以停用應用程式,以便在啟動應用程式時提供內容。 (Windows Phone 8.x 應用程式)

DefaultFileExtension

重要

請勿使用這個屬性。 請改用 FileTypeChoices 屬性 。 預設副檔名是由 FileTypeChoices中第一個檔案類型群組中的第一個檔案類型所設定。

取得或設定 fileSavePicker 提供給要儲存之檔案的預設副檔名。

EnterpriseId

取得或設定識別碼,指定擁有檔案的企業。

FileTypeChoices

取得使用者可以選擇指派給檔案的有效檔案類型集合。

SettingsIdentifier

取得或設定與目前 FileSavePicker 實例相關聯的設定識別碼。

SuggestedFileName

取得或設定檔案儲存選擇器向使用者建議的檔案名。

SuggestedSaveFile

取得或設定檔案選擇器建議給使用者儲存檔案的 storageFile

SuggestedStartLocation

取得或設定檔案儲存選擇器建議給使用者的位置做為儲存檔案的位置。

User

取得 建立 FileSavePicker 之使用者的相關資訊。 針對 多使用者應用程式使用這個屬性。

方法

CreateForUser(User)

建立 FileSavePicker ,其範圍限定為指定之使用者的個人目錄。 針對 多使用者應用程式使用這個方法。

PickSaveFileAndContinue()

從Windows 10起過時;請改用PickSaveFileAsync 顯示檔案選擇器,讓使用者可以儲存檔案、停用和應用程式,並在作業完成時重新啟用它。 (Windows Phone 8.x 應用程式)

PickSaveFileAsync()

顯示檔案選擇器,讓使用者可以儲存檔案,並設定要儲存之檔案的檔案名、副檔名和位置。 (UWP app)

適用於

另請參閱