yotiky Tech Blog

とあるエンジニアの備忘録

C# - FileSavePicker で開いたファイルピッカーをコードから閉じる

FileSavePicker

FileSavePickerについてはこちらから。

learn.microsoft.com

上記で紹介しているサンプルプロジェクトはこちら。

github.com

サンプル実装

元コード

サンプルプロジェクトを簡略化したコードは以下の通り。

private async void SaveFileButton_Click(object sender, RoutedEventArgs e)
{
    OutputTextBlock.Text = "";
    FileSavePicker savePicker = new FileSavePicker();
    StorageFile file = await savePicker.PickSaveFileAsync();
    if (file != null)
    {
        // fileに対する処理(省略)
        OutputTextBlock.Text = "File " + file.Name + " was saved.";
    }
    else
    {
        OutputTextBlock.Text = "Operation cancelled.";
    }
}

キャンセル処理

ファイルピッカーを閉じるには、IAsyncOperationCancel する。

private IAsyncOperation<StorageFile> _asyncOperation;

private async void SaveFileButton_Click(object sender, RoutedEventArgs e)
{
    OutputTextBlock.Text = "";
    FileSavePicker savePicker = new FileSavePicker();
    _asyncOperation = savePicker.PickSaveFileAsync();

    StorageFile file;
    try
    {
        file = await _asyncOperation;
    }
    catch (TaskCanceledException)
    {
        file = null;
    }
    finally
    {
        _asyncOperation = null;
    }

    if (file != null)
    {
        // fileに対する処理(省略)
        OutputTextBlock.Text = "File " + file.Name + " was saved.";
    }
    else
    {
        OutputTextBlock.Text = "Operation cancelled.";
    }
}

public void Cancel()
{
    if (_asyncOperation?.Status == Windows.Foundation.AsyncStatus.Started)
        _asyncOperation.Cancel();
}

とりあえず試すだけなら、Delay でキャンセルするようにすれば動作を確認できる。

var asyncOp = savePicker.PickSaveFileAsync();

Task.Run(async () =>
{
    await Task.Delay(5000);

    if (asyncOp.Status == Windows.Foundation.AsyncStatus.Started)
        asyncOp.Cancel();
});