- Открытие файлов и папок с помощью средства выбора Open files and folders with a picker
- Предварительные условия Prerequisites
- Пользовательский интерфейс средства выбора файлов File picker UI
- Как работают средства выбора How pickers work
- Выбор одного файла: полный код Pick a single file: complete code listing
- Выбор одного файла: пошаговые инструкции Pick a single file: step-by-step
- Выбор папки: полный код Pick a folder: complete code listing
- Open files and folders with a picker
- Prerequisites
- File picker UI
- How pickers work
- Pick a single file: complete code listing
- Pick a single file: step-by-step
- Pick a folder: complete code listing
Открытие файлов и папок с помощью средства выбора Open files and folders with a picker
Важные API Important APIs
Получите доступ к файлам и папкам, разрешив пользователю взаимодействовать со средством выбора. Access files and folders by letting the user interact with a picker. Для получения доступа к файлам можно использовать классы FileOpenPicker и FileSavePicker, а для получения доступа к папкам — класс FolderPicker. You can use the FileOpenPicker and FileSavePicker classes to access files, and the FolderPicker to access a folder.
Предварительные условия Prerequisites
Общее представление об асинхронном программировании для приложений универсальной платформы Windows (UWP) . Understand async programming for Universal Windows Platform (UWP) apps
Описание процесса написания асинхронных приложений на C# или Visual Basic см. в статье Вызов асинхронных API в C# и Visual Basic. You can learn how to write asynchronous apps in C# or Visual Basic, see Call asynchronous APIs in C# or Visual Basic. Сведения о создании асинхронных приложений на C++ см. в статье Асинхронное программирование на языке C++. To learn how to write asynchronous apps in C++, see Asynchronous programming in C++.
Права доступа к расположению Access permissions to the location
Пользовательский интерфейс средства выбора файлов File picker UI
В средстве выбора файлов отображаются сведения, позволяющие сориентировать пользователей и обеспечить им привычное взаимодействие с системой при открытии и сохранении файлов. A file picker displays information to orient users and provide a consistent experience when opening or saving files.
Эти сведения включают следующее: That information includes:
- текущее расположение; The current location
- выбранный пользователем элемент или несколько элементов; The item or items that the user picked
- дерево расположений, к которым может перейти пользователь. A tree of locations that the user can browse to. Они включают расположения в файловой системе, например папку «Музыка» или «Загрузки», а также приложения, которые реализуют контракт средства выбора файлов (такие как «Камера», «Фотографии» и Microsoft OneDrive). These locations include file system locations—such as the Music or Downloads folder—as well as apps that implement the file picker contract (such as Camera, Photos, and Microsoft OneDrive).
Почтовое приложение может отображать средство выбора файлов, чтобы предоставить пользователю возможность выбора вложений. An email app might display a file picker for the user to pick attachments.
Как работают средства выбора How pickers work
Используя средство выбора, ваше приложение может получать доступ к файлам и папкам в системе пользователя, просматривать и сохранять их. With a picker your app can access, browse, and save files and folders on the user’s system. Ваше приложение получает эти выбранные элементы в виде объектов StorageFile и StorageFolder, с которыми потом можно работать. Your app receives those picks as StorageFile and StorageFolder objects, which you can then operate on.
Средство выбора использует единый унифицированный интерфейс для обеспечения пользователю возможности выбора файлов и папок из файловой системы либо из других приложений. The picker uses a single, unified interface to let the user pick files and folders from the file system or from other apps. Файлы, выбранные из других приложений, воспринимаются как файлы из файловой системы: они возвращаются как объекты StorageFile. Files picked from other apps are like files from the file system: they are returned as StorageFile objects. В целом ваше приложение может работать с ними так же, как с другими объектами. In general, your app can operate on them in the same ways as other objects. Другие приложения обеспечивают доступ к файлам за счет участия в контрактах средства выбора файлов. Other apps make files available by participating in file picker contracts. Сведения о настройке вашего приложения для предоставления другим приложениям файлов, места сохранения или обновлений файлов см. в разделе Взаимодействие с контрактами «Средство выбора файлов». If you want your app to provide files, a save location, or file updates to other apps, see Integrating with file picker contracts.
Например, вы можете вызывать средство выбора файлов в своем приложении, чтобы пользователь имел возможность открыть необходимый файл. For example, you might call the file picker in your app so that your user can open a file. За счет этого ваше приложение становится вызывающим приложением. This makes your app the calling app. Средство выбора файлов взаимодействует с системой и/или другими приложениями, обеспечивая пользователю возможность поиска и выбора определенного файла. The file picker interacts with the system and/or other apps to let the user navigate and pick the file. Когда пользователь выбирает файл, средство выбора файлов возвращает этот файл в ваше приложение. When your user chooses a file, the file picker returns that file to your app. Ниже показан процесс, который имеет место при выборе пользователем файла из другого приложения, например OneDrive. Here’s the process for the case of the user choosing a file from a providing app, such as OneDrive.
Выбор одного файла: полный код Pick a single file: complete code listing
Выбор одного файла: пошаговые инструкции Pick a single file: step-by-step
Использование средства выбора файлов включает создание и настройку объекта «средство выбора файлов» и отображение средства выбора файлов, чтобы дать пользователю возможность выбрать один или несколько элементов. Using a file picker involves creating and customizing a file picker object, and then showing the file picker so the user can pick one or more items.
Создание и настройка FileOpenPicker Create and customize a FileOpenPicker
Задайте свойства объекта «средство выбора файлов», соответствующие вашим пользователям и приложению. Set properties on the file picker object relevant to your users and app.
Этот пример создает сложное визуальное отображение в виде картинок в подходящем расположении, которое пользователь может выбрать, установив три свойства: ViewMode, SuggestedStartLocation и FileTypeFilter. This example creates a rich, visual display of pictures in a convenient location that the user can pick from by setting three properties: ViewMode, SuggestedStartLocation, and FileTypeFilter.
Задание для свойства ViewMode значения Thumbnail перечисления PickerViewMode создает сложное визуальное представление за счет эскизов изображений, представляющих файлы в средстве выбора файлов. Setting ViewMode to the PickerViewMode Thumbnail enum value creates a rich, visual display by using picture thumbnails to represent files in the file picker. Выполните это, чтобы выбрать визуальные файлы, например фотографии или видео. Do this for picking visual files such as pictures or videos. В других случаях воспользуйтесь PickerViewMode.List. Otherwise, use PickerViewMode.List. Гипотетическое почтовое приложение с функциями Прикрепить изображение или видео и Прикрепить документ установит свойство ViewMode, соответствующее функции, прежде чем отобразить средство выбора файлов. A hypothetical email app with Attach Picture or Video and Attach Document features would set the ViewMode appropriate to the feature before showing the file picker.
Выбор библиотеки «Изображения» в качестве значения для параметра SuggestedStartLocation с помощью PickerLocationId.PicturesLibrary позволяет пользователю начать работу в расположении вероятного нахождения изображений. Setting SuggestedStartLocation to Pictures using PickerLocationId.PicturesLibrary starts the user in a location where they’re likely to find pictures. Присвойте свойство SuggestedStartLocation расположению, подходящему для типа выбранных файлов, например «Музыка», «Изображения», «Видео» или «Документы». Set SuggestedStartLocation to a location appropriate for the type of file being picked, for example Music, Pictures, Videos, or Documents. Из начального расположения пользователь может перейти в другие расположения. From the start location, the user can navigate to other locations.
Использование FileTypeFilter для указания типов файлов сохраняет внимание пользователя на выборе соответствующих файлов. Using FileTypeFilter to specify file types keeps the user focused on picking files that are relevant. Чтобы заменить предыдущие типы файлов в FileTypeFilter новыми записями, используйте вместо метода Add метод ReplaceAll. To replace previous file types in the FileTypeFilter with new entries, use ReplaceAll instead of Add.
Отображение FileOpenPicker Show the FileOpenPicker
Выбор одного файла To pick a single file
Выбор нескольких файлов To pick multiple files
Выбор папки: полный код Pick a folder: complete code listing
Каждый раз, когда ваше приложение получает доступ к файлу или папке через средство выбора, добавляйте этот файл или папку в свойство FutureAccessList или MostRecentlyUsedList приложения для отслеживания. Whenever your app accesses a file or folder through a picker, add it to your app’s FutureAccessList or MostRecentlyUsedList to keep track of it. Подробнее об использовании этих списков см. в разделе Отслеживание последних использованных файлов и папок. You can learn more about using these lists in How to track recently-used files and folders.
Open files and folders with a picker
Important APIs
Access files and folders by letting the user interact with a picker. You can use the FileOpenPicker and FileSavePicker classes to access files, and the FolderPicker to access a folder.
В For a complete sample, see the File picker sample.
Prerequisites
Understand async programming for Universal Windows Platform (UWP) apps
You can learn how to write asynchronous apps in C# or Visual Basic, see Call asynchronous APIs in C# or Visual Basic. To learn how to write asynchronous apps in C++, see Asynchronous programming in C++.
Access permissions to the location
File picker UI
A file picker displays information to orient users and provide a consistent experience when opening or saving files.
That information includes:
- The current location
- The item or items that the user picked
- A tree of locations that the user can browse to. These locations include file system locations—such as the Music or Downloads folder—as well as apps that implement the file picker contract (such as Camera, Photos, and Microsoft OneDrive).
An email app might display a file picker for the user to pick attachments.
How pickers work
With a picker your app can access, browse, and save files and folders on the user’s system. Your app receives those picks as StorageFile and StorageFolder objects, which you can then operate on.
The picker uses a single, unified interface to let the user pick files and folders from the file system or from other apps. Files picked from other apps are like files from the file system: they are returned as StorageFile objects. In general, your app can operate on them in the same ways as other objects. Other apps make files available by participating in file picker contracts. If you want your app to provide files, a save location, or file updates to other apps, see Integrating with file picker contracts.
For example, you might call the file picker in your app so that your user can open a file. This makes your app the calling app. The file picker interacts with the system and/or other apps to let the user navigate and pick the file. When your user chooses a file, the file picker returns that file to your app. Here’s the process for the case of the user choosing a file from a providing app, such as OneDrive.
Pick a single file: complete code listing
Pick a single file: step-by-step
Using a file picker involves creating and customizing a file picker object, and then showing the file picker so the user can pick one or more items.
Create and customize a FileOpenPicker
Set properties on the file picker object relevant to your users and app.
This example creates a rich, visual display of pictures in a convenient location that the user can pick from by setting three properties: ViewMode, SuggestedStartLocation, and FileTypeFilter.
Setting ViewMode to the PickerViewMode Thumbnail enum value creates a rich, visual display by using picture thumbnails to represent files in the file picker. Do this for picking visual files such as pictures or videos. Otherwise, use PickerViewMode.List. A hypothetical email app with Attach Picture or Video and Attach Document features would set the ViewMode appropriate to the feature before showing the file picker.
Setting SuggestedStartLocation to Pictures using PickerLocationId.PicturesLibrary starts the user in a location where they’re likely to find pictures. Set SuggestedStartLocation to a location appropriate for the type of file being picked, for example Music, Pictures, Videos, or Documents. From the start location, the user can navigate to other locations.
Using FileTypeFilter to specify file types keeps the user focused on picking files that are relevant. To replace previous file types in the FileTypeFilter with new entries, use ReplaceAll instead of Add.
Show the FileOpenPicker
To pick a single file
To pick multiple files
Pick a folder: complete code listing
Whenever your app accesses a file or folder through a picker, add it to your app’s FutureAccessList or MostRecentlyUsedList to keep track of it. You can learn more about using these lists in How to track recently-used files and folders.