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 メソッドを呼び出す前に 1 つ以上のファイルの種類を指定するには、 FileTypeChoices プロパティ を使用する必要があります。または、ピッカーによって例外がスローされます。

ファイル ピッカーを使用してファイルを保存する方法については、「ファイル ピッカーを使用してファイルを保存する方法」を参照してください。

ファイルとフォルダーのファイル ピッカーへのアクセスを開始するには、「 ファイル、フォルダー、およびライブラリ 」を参照してください。

警告

アプリのスナップ中にファイル ピッカーを表示しようとすると、ファイル ピッカーは表示されず、例外がスローされます。 これを回避するには、アプリがスナップされていないことを確認するか、ファイル ピッカーを呼び出す前にスナップを解除します。 次のコード例と ファイル ピッカーのサンプル では、その方法を示します。

昇格を必要とするデスクトップ アプリの場合

デスクトップ アプリ (WinUI 3 アプリを含む) では、 FileSavePicker (および Windows.Storage.Pickers のその他の種類) を使用できます。 ただし、デスクトップ アプリの実行に昇格が必要な場合は、別のアプローチが必要になります (これは、これらの API が昇格されたアプリで使用されるように設計されていないためです)。 次のコード スニペットは、 C#/Win32 P/Invoke Source Generator (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

ファイルを所有するエンタープライズを指定する ID を取得または設定します。

FileTypeChoices

ユーザーがファイルに割り当てることができる有効なファイルの種類のコレクションを取得します。

SettingsIdentifier

現在の FileSavePicker インスタンスに関連付けられている設定識別子を取得または設定します。

SuggestedFileName

ファイル保存ピッカーがユーザーに提案するファイル名を取得または設定します。

SuggestedSaveFile

ファイルピッカーがファイルを保存するためにユーザーに提案する storageFile を取得または設定します。

SuggestedStartLocation

ファイル保存ピッカーがファイルを保存する場所としてユーザーに提案する場所を取得または設定します。

User

FileSavePicker が作成されたユーザーに関する情報を取得します。 マルチユーザー アプリケーションには、このプロパティを使用します。

メソッド

CreateForUser(User)

指定したユーザーの個人用ディレクトリをスコープとする FileSavePicker を作成します。 マルチユーザー アプリケーションには、このメソッドを使用します。

PickSaveFileAndContinue()

Windows 10現在は廃止されました。代わりに PickSaveFileAsync を使用してください。 ファイル ピッカーを表示して、ユーザーがファイルを保存し、非アクティブ化して、操作が完了したときにアプリを再アクティブ化できるようにします。 (Windows Phone 8.x アプリ)

PickSaveFileAsync()

ファイル ピッカーを表示して、ユーザーがファイルを保存し、保存するファイルの名前、拡張子、および場所を設定できるようにします。 (UWP アプリ)

適用対象

こちらもご覧ください