访问家庭组内容Accessing HomeGroup content

重要的 APIImportant APIs

访问存储在用户的“家庭组”文件夹中的内容,包括图片、音乐和视频。Access content stored in the user's HomeGroup folder, including pictures, music, and videos.

必备条件Prerequisites

  • 了解通用 Windows 平台 (UWP) 应用的异步编程Understand async programming for Universal Windows Platform (UWP) apps

    若要了解如何使用 C# 或 Visual Basic 编写异步应用,请参阅使用 C# 或 Visual Basic 调用异步 APIYou 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++.

  • 应用功能声明App capabilty declarations

    若要访问家庭组内容,用户的计算机必须已设置家庭组,且你的应用必须至少具有以下功能之一:picturesLibrarymusicLibraryvideosLibraryTo access HomeGroup content, the user's machine must have a HomeGroup set up and your app must have at least one of the following capabilities: picturesLibrary, musicLibrary, or videosLibrary. 当你的应用访问“家庭组”文件夹时,它将仅看到与在你的应用清单中声明的功能相对应的库。When your app accesses the HomeGroup folder, it will see only the libraries that correspond to the capabilities declared in your app's manifest. 若要了解详细信息,请参阅文件访问权限To learn more, see File access permissions.

    备注

     无论在应用清单中声明了什么功能,也无论用户的共享设置如何,你的应用都看不到家庭组的文档库中的内容。 Content in the Documents library of a HomeGroup isn't visible to your app regardless of the capabilities declared in your app's manifest and regardless of the user's sharing settings.  

  • 了解如何使用文件选取器Understand how to use file pickers

    你通常使用文件选取器访问家庭组中的文件和文件夹。You typically use the file picker to access files and folders in the HomeGroup. 若要了解如何使用文件选取器,请参阅使用选取器打开文件和文件夹To learn how to use the file picker, see Open files and folders with a picker.

  • 了解文件和文件夹查询Understand file and folder queries

    你可以使用查询来枚举家庭组中的文件和文件夹。You can use queries to enumerate files and folders in the HomeGroup. 若要了解有关文件和文件夹查询的信息,请参阅枚举和查询文件和文件夹To learn about file and folder queries, see Enumerating and querying files and folders.

在家庭组打开文件选取器Open the file picker at the HomeGroup

按以下步骤打开文件选取器的一个实例,让用户从家庭组中选取文件和文件夹:Follow these steps to open an instance of the file picker that lets the user pick files and folders from the HomeGroup:

  1. 创建并自定义文件选取器Create and customize the file picker

    使用 FileOpenPicker 创建文件选取器,然后将选取器的 SuggestedStartLocation 设置为 PickerLocationId.HomeGroupUse FileOpenPicker to create the file picker, and then set the picker's SuggestedStartLocation to PickerLocationId.HomeGroup. 或者,设置与你的用户和你的应用相关的其他属性。Or, set other properties that are relevant to your users and your app. 有关帮助你确定如何自定义文件选取器的指南,请参阅文件选取器指南和清单For guidelines to help you decide how to customize the file picker, see Guidelines and checklist for file pickers

    此示例创建了一个在家庭组打开的文件选取器,包含任何类型的文件,并将文件显示为缩略图图像:This example creates a file picker that opens at the HomeGroup, includes files of any type, and displays the files as thumbnail images:

    Windows.Storage.Pickers.FileOpenPicker picker = new Windows.Storage.Pickers.FileOpenPicker();
    picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
    picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.HomeGroup;
    picker.FileTypeFilter.Clear();
    picker.FileTypeFilter.Add("*");
    
  2. 显示文件选取器并处理已选取的文件。Show the file picker and process the picked file.

    在你创建并自定义文件选取器之后,让用户通过调用 FileOpenPicker.PickSingleFileAsync 来选取一个文件,或通过调用 FileOpenPicker.PickMultipleFilesAsync 来选取多个文件。After you create and customize the file picker, let the user pick one file by calling FileOpenPicker.PickSingleFileAsync, or multiple files by calling FileOpenPicker.PickMultipleFilesAsync.

    此示例显示文件选取器以让用户选取一个文件:This example displays the file picker to let the user pick one file:

    Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();
    
    if (file != null)
    {
        // Do something with the file.
    }
    else
    {
        // No file returned. Handle the error.
    }   
    

在家庭组中搜索文件Search the HomeGroup for files

此部分显示了如何找到与用户提供的查询词匹配的家庭组项目。This section shows how to find HomeGroup items that match a query term provided by the user.

  1. 从用户获取查询词。Get the query term from the user.

    下面我们将获取一个用户已输入到某个称为 searchQueryTextBoxTextBox 控件中的查询词:Here we get a query term that the user has entered into a TextBox control called searchQueryTextBox:

    string queryTerm = this.searchQueryTextBox.Text;    
    
  2. 设置查询选项和搜索筛选器。Set the query options and search filter.

    查询选项确定搜索结果是如何进行排序的,而搜索筛选器确定哪些项目包含在搜索结果中。Query options determine how the search results are sorted, while the search filter determines which items are included in the search results.

    此示例设置先按相关性然后按修改日期对搜索结果进行排序的查询选项。This example sets query options that sort the search results by relevance and then the date modified. 搜索筛选器是用户在上一步中输入的查询词:The search filter is the query term that the user entered in the previous step:

    Windows.Storage.Search.QueryOptions queryOptions =
            new Windows.Storage.Search.QueryOptions
                (Windows.Storage.Search.CommonFileQuery.OrderBySearchRank, null);
    queryOptions.UserSearchFilter = queryTerm.Text;
    Windows.Storage.Search.StorageFileQueryResult queryResults =
            Windows.Storage.KnownFolders.HomeGroup.CreateFileQueryWithOptions(queryOptions);    
    
  3. 运行查询并处理结果。Run the query and process the results.

    以下示例在家庭组中运行搜索查询并将任何匹配的文件的名称另存为一个字符串列表。The following example runs the search query in the HomeGroup and saves the names of any matching files as a list of strings.

    System.Collections.Generic.IReadOnlyList<Windows.Storage.StorageFile> files =
        await queryResults.GetFilesAsync();
    
    if (files.Count > 0)
    {
        outputString += (files.Count == 1) ? "One file found\n" : files.Count.ToString() + " files found\n";
        foreach (Windows.Storage.StorageFile file in files)
        {
            outputString += file.Name + "\n";
        }
    }    
    

在家庭组中搜索某个特定用户的共享文件Search the HomeGroup for a particular user's shared files

此部分介绍如何查找由特定用户共享的家庭组文件。This section shows you how to find HomeGroup files that are shared by a particular user.

  1. 获取家庭组用户的集合。Get a collection of HomeGroup users.

    家庭组中每个第一级文件夹表示单个家庭组用户。Each of the first-level folders in the HomeGroup represents an individual HomeGroup user. 因此,若要获取家庭组用户的集合,请调用 GetFoldersAsync 检索顶级家庭组文件夹。So, to get the collection of HomeGroup users, call GetFoldersAsync retrieve the top-level HomeGroup folders.

    System.Collections.Generic.IReadOnlyList<Windows.Storage.StorageFolder> hgFolders =
        await Windows.Storage.KnownFolders.HomeGroup.GetFoldersAsync();    
    
  2. 查找目标用户的文件夹,然后创建一个限定于该用户的文件夹的文件查询。Find the target user's folder, and then create a file query scoped to that user's folder.

    以下示例循环访问检索的文件夹以查找目标用户的文件夹。The following example iterates through the retrieved folders to find the target user's folder. 然后,它设置查询选项以查找文件夹中的所有文件,这些文件先按相关性然后按数据修改日期进行排序。Then, it sets query options to find all files in the folder, sorted first by relevance and then by the date modified. 此示例构建一个字符串,此字符串报告找到的文件数以及文件的名称。The example builds a string that reports the number of files found, along with the names of the files.

    bool userFound = false;
    foreach (Windows.Storage.StorageFolder folder in hgFolders)
    {
        if (folder.DisplayName == targetUserName)
        {
            // Found the target user's folder, now find all files in the folder.
            userFound = true;
            Windows.Storage.Search.QueryOptions queryOptions =
                new Windows.Storage.Search.QueryOptions
                    (Windows.Storage.Search.CommonFileQuery.OrderBySearchRank, null);
            queryOptions.UserSearchFilter = "*";
            Windows.Storage.Search.StorageFileQueryResult queryResults =
                folder.CreateFileQueryWithOptions(queryOptions);
            System.Collections.Generic.IReadOnlyList<Windows.Storage.StorageFile> files =
                await queryResults.GetFilesAsync();
    
            if (files.Count > 0)
            {
                string outputString = "Searched for files belonging to " + targetUserName + "'\n";
                outputString += (files.Count == 1) ? "One file found\n" : files.Count.ToString() + " files found\n";
                foreach (Windows.Storage.StorageFile file in files)
                {
                    outputString += file.Name + "\n";
                }
            }
        }
    }    
    

从家庭组流式传输视频Stream video from the HomeGroup

请按以下步骤从家庭组流式传输视频内容:Follow these steps to stream video content from the HomeGroup:

  1. 在应用中包含一个 MediaElement。Include a MediaElement in your app.

    MediaElement 允许你在你的应用中播放音频和视频内容。A MediaElement lets you play back audio and video content in your app. 有关音频和视频播放的详细信息,请参阅创建自定义传输控件音频、视频和相机For more information on audio and video playback, see Create custom transport controls and Audio, video, and camera.

    <Grid x:Name="Output" HorizontalAlignment="Left" VerticalAlignment="Top" Grid.Row="1">
        <MediaElement x:Name="VideoBox" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0" Width="400" Height="300"/>
    </Grid>    
    
  2. 在家庭组打开某个文件选取器,并应用某个筛选器,该筛选器包含采用你的应用支持的格式的视频文件。Open a file picker at the HomeGroup and apply a filter that includes video files in the formats that your app supports.

    此示例在文件打开选取器中包含 .mp4 和 .wmv 文件。This example includes .mp4 and .wmv files in the file open picker.

    Windows.Storage.Pickers.FileOpenPicker picker = new Windows.Storage.Pickers.FileOpenPicker();
    picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
    picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.HomeGroup;
    picker.FileTypeFilter.Clear();
    picker.FileTypeFilter.Add(".mp4");
    picker.FileTypeFilter.Add(".wmv");
    Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();   
    
  3. 打开用户选择的文件以进行读取访问,并将文件流设置为 MediaElement 的源,然后播放该文件。Open the user's file selection for read access, and set the file stream as the source for the MediaElement, and then play the file.

    if (file != null)
    {
        var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
        VideoBox.SetSource(stream, file.ContentType);
        VideoBox.Stop();
        VideoBox.Play();
    }
    else
    {
        // No file selected. Handle the error here.
    }