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 속성 속성을 사용하여 하나 이상의 파일 형식을 지정해야 합니다. 그렇지 않으면 선택기가 예외를 throw합니다.

파일 선택기를 통해 파일을 저장하는 방법을 알아보려면 파일 선택기를 통해 파일을 저장하는 방법을 참조하세요.

파일 및 폴더 파일 선택기 액세스를 시작하려면 파일, 폴더 및 라이브러리 를 참조하세요 .

경고

앱이 스냅되는 동안 파일 선택기를 표시하려고 하면 파일 선택기가 표시되지 않고 예외가 throw됩니다. 앱이 스냅되지 않도록 하거나 파일 선택기를 호출하기 전에 스냅 해제하여 이를 방지할 수 있습니다. 다음 코드 예제와 파일 선택기 샘플 에서 방법을 보여 줍니다.

권한 상승이 필요한 데스크톱 앱에서

데스크톱 앱(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 사용자

생성자

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 앱)

적용 대상

추가 정보