Sdílet prostřednictvím


Kurz: Otevírání souborů a složek pomocí výběrů ve WinUI

Pomocí nástroje pro výběr souborů a složek Windows App SDK umožníte uživatelům procházet a vybírat soubory nebo složky v aplikaci WinUI. Rozhraní API pro výběr položek poskytují známé prostředí Windows, které uživatelům pomáhá procházet jejich zařízení a cloudová úložiště. V tomto článku se dozvíte, jak implementovat nástroje pro výběr souborů a výběr složky, přizpůsobit jejich chování a zpracovat vybrané výsledky ve vaší aplikaci.

Třídy Windows App SDK FileOpenPicker a FileSavePicker vytvářejí dialogové okno pro výběr, které uživatelům umožňuje zadat název a umístění souboru, který chcete otevřít nebo uložit. Třída FolderPicker umožňuje vybrat složku.

Další informace o použití nástroje pro výběr k ukládání souborů najdete v tématu Uložení souboru pomocí výběru Windows App SDK.

Důležitá rozhraní API

Tento článek používá následující rozhraní API:

Uživatelské rozhraní pro výběr souborů

Výběr souborů zobrazuje informace k orientaci uživatelů a zajišťuje konzistentní zážitek při otevírání nebo ukládání souborů.

Mezi tyto informace patří:

  • Aktuální umístění
  • Položka nebo položky, které uživatel vybere
  • Strom lokalit, který může uživatel procházet. Tato umístění zahrnují umístění systému souborů, jako je například složka Hudba nebo Stažené soubory, a také aplikace, které implementují kontrakt pro výběr souborů (například Fotoaparát, Fotky a Microsoft OneDrive).

Možná máte aplikaci, která umožňuje uživatelům otevírat nebo ukládat soubory. Když uživatel spustí danou akci, aplikace zavolá výběr souboru, který zobrazí uživatelské rozhraní pro výběr souboru:

Snímek obrazovky s výběrem filtru, který zobrazuje soubory .txt, .pdf, .doc a .docx

Jak fungují nástroje pro výběr s vaší aplikací

Pomocí nástroje pro výběr může vaše aplikace přistupovat, procházet a ukládat soubory a složky v systému uživatele. Vaše aplikace obdrží tyto výběry jako objekty PickFileResult a PickFolderResult odlehčené, které poskytují cestu k vybranému souboru nebo složce.

Nástroj pro výběr používá jedno sjednocené rozhraní, které umožňuje uživateli vybrat soubory a složky ze systému souborů nebo z jiných aplikací. Soubory vybrané z jiných aplikací se podobají souborům ze systému souborů. Obecně platí, že vaše aplikace s nimi může pracovat stejným způsobem jako jiné objekty. Ostatní aplikace zpřístupňují soubory tím, že se účastní kontraktů pro výběr souborů.

Můžete například využít selektor souborů ve své aplikaci, aby uživatel mohl otevřít soubor. Tato akce způsobí, že aplikace bude volající aplikací. Výběr souboru komunikuje se systémem a dalšími aplikacemi, aby uživatel může procházet a vybírat soubor. Když uživatel vybere soubor, vrátí nástroj pro výběr souboru cestu k vaší aplikaci.

Výběr souboru pro otevření příkladu

Následující kód ukazuje, jak pomocí Třídy FileOpenPicker umožnit uživateli vybrat jeden soubor, například fotku. Kód nastaví vlastnosti pro výběr tak, aby přizpůsobil jeho vzhled a chování, a pak zobrazí výběr pro uživatele pomocí PickSingleFileAsync metoda. Pokud uživatel vybere soubor, aplikace přečte obsah souboru a uloží ho do proměnné.

using Microsoft.Windows.Storage.Pickers;

var openPicker = new FileOpenPicker(this.AppWindow.Id)
{
    // (Optional) Specify the initial location for the picker. 
    //     If the specified location doesn't exist on the user's machine, it falls back to the DocumentsLibrary.
    //     If not set, it defaults to PickerLocationId.Unspecified, and the system will use its default location.
    SuggestedStartLocation = PickerLocationId.DocumentsLibrary,
    
    // (Optional) specify the text displayed on the commit button. 
    //     If not specified, the system uses a default label of "Open" (suitably translated).
    CommitButtonText = "Choose selected files",

    // (Optional) specify file extension filters. If not specified, defaults to all files (*.*).
    FileTypeFilter = { ".txt", ".pdf", ".doc", ".docx" },

    // (Optional) specify the view mode of the picker dialog. If not specified, defaults to List.
    ViewMode = PickerViewMode.List,
};

var result = await openPicker.PickSingleFileAsync();
if (result is not null)
{
    var content = System.IO.File.ReadAllText(result.Path);
}
else
{
    // Add your error handling here.
}
#include <winrt/Microsoft.Windows.Storage.Pickers.h>
#include <fstream>
#include <string>

using namespace winrt::Microsoft::Windows::Storage::Pickers;

FileOpenPicker openPicker(this->AppWindow().Id());

// (Optional) Specify the initial location for the picker. 
//     If the specified location doesn't exist on the user's machine, it falls back to the DocumentsLibrary.
//     If not set, it defaults to PickerLocationId.Unspecified, and the system will use its default location.
openPicker.SuggestedStartLocation(PickerLocationId::DocumentsLibrary);

// (Optional) specify the text displayed on the commit button. 
//     If not specified, the system uses a default label of "Open" (suitably translated).
openPicker.CommitButtonText(L"Choose selected files");

// (Optional) specify file extension filters. If not specified, defaults to all files (*.*).
openPicker.FileTypeFilter().ReplaceAll({ L".txt", L".pdf", L".doc", L".docx" });

// (Optional) specify the view mode of the picker dialog. If not specified, defaults to List.
openPicker.ViewMode(PickerViewMode::List);

auto result{ co_await openPicker.PickSingleFileAsync() };
if (result)
{
    std::ifstream fileReader(result.Path().c_str());
    std::string text((std::istreambuf_iterator<char>(fileReader)), std::istreambuf_iterator<char>());
    winrt::hstring hText = winrt::to_hstring(text);
}
else
{
    // Add your error handling here.
}

Výběr více souborů pro otevření příkladu

Můžete také nechat uživatele vybrat více souborů. Následující kód ukazuje, jak pomocí FileOpenPicker třídy umožnit uživateli vybrat více souborů, jako jsou fotky. Proces je stejný, ale Metoda PickMultipleFilesAsync vrátí kolekci cest k souborům místo jedné cesty.

using Microsoft.Windows.Storage.Pickers;

var openPicker = new FileOpenPicker(this.AppWindow.Id);

var results = await openPicker.PickMultipleFilesAsync();
if (results.Count > 0)
{
    var pickedFilePaths = results.Select(f => f.Path);
    foreach (var path in pickedFilePaths)
    {
        var content = System.IO.File.ReadAllText(path);
    }
}
else
{
    // Add your error handling here.
}
#include <winrt/Microsoft.Windows.Storage.Pickers.h>
#include <fstream>
#include <string>

using namespace winrt::Microsoft::Windows::Storage::Pickers;

FileOpenPicker openPicker(this->AppWindow().Id());
auto results{ co_await openPicker.PickMultipleFilesAsync() };
if (results.Size() > 0)
{
    for (auto const& result : results)
    {
        std::ifstream fileReader(result.Path().c_str());
        std::string text((std::istreambuf_iterator<char>(fileReader)), std::istreambuf_iterator<char>());
        winrt::hstring hText = winrt::to_hstring(text);
    }
}
else
{
    // Add your error handling here.
}

Výběr příkladu složky

Pokud chcete vybrat složku pomocí třídy FolderPicker , použijte následující kód. Tento kód vytvoří výběr složky, zobrazí ho uživateli pomocí PickSingleFolderAsync metoda a načte cestu vybrané složky v PickFolderResult objektu. Pokud uživatel vybere složku, aplikace načte cestu ke složce a uloží ji do proměnné pro pozdější použití.

using Microsoft.Windows.Storage.Pickers;

var folderPicker = new FolderPicker(this.AppWindow.Id)
{
    // (Optional) Specify the initial location for the picker. 
    //     If the specified location doesn't exist on the user's machine, it falls back to the DocumentsLibrary.
    //     If not set, it defaults to PickerLocationId.Unspecified, and the system will use its default location.
    SuggestedStartLocation = PickerLocationId.DocumentsLibrary,

    // (Optional) specify the text displayed on the commit button. 
    //     If not specified, the system uses a default label of "Open" (suitably translated).
    CommitButtonText = "Select Folder",

    // (Optional) specify the view mode of the picker dialog. If not specified, default to List.
    ViewMode = PickerViewMode.List,
};

var result = await folderPicker.PickSingleFolderAsync();

if (result is not null)
{
    var path = result.Path;
}
else
{
    // Add your error handling here.
}
#include <winrt/Microsoft.Windows.Storage.Pickers.h>

using namespace winrt::Microsoft::Windows::Storage::Pickers;

FolderPicker folderPicker(this->AppWindow().Id());

// (Optional) Specify the initial location for the picker. 
//     If the specified location doesn't exist on the user's machine, it falls back to the DocumentsLibrary.
//     If not set, it defaults to PickerLocationId.Unspecified, and the system will use its default location.
folderPicker.SuggestedStartLocation(PickerLocationId::DocumentsLibrary);

// (Optional) specify the text displayed on the commit button. 
//     If not specified, the system uses a default label of "Open" (suitably translated).
folderPicker.CommitButtonText(L"Select Folder");

// (Optional) specify the view mode of the picker dialog. If not specified, default to List.
folderPicker.ViewMode(PickerViewMode::List);

auto result{ co_await folderPicker.PickSingleFolderAsync() };
if (result)
{
    auto path{ result.Path() };
}
else
{
    // Add your error handling here.
}

Návod

Pokaždé, když aplikace přistupuje k souboru nebo složce pomocí nástroje pro výběr, přidejte ho do FutureAccessList nebo MostRecentlyUsedList a sledujte ji pomocí rozhraní API Windows Runtime (WinRT). Další informace naleznete v tématu Sledování naposledy použitých souborů a složek.

Uživatelské rozhraní pro výběr složky vypadá takto:

Snímek obrazovky s výběrem složky, která zobrazuje jednotku C

Windows. Storage.Pickers

Soubory, složky a knihovny s Windows App SDK

Microsoft.Windows.Storage.Pickers namespace