存取 HomeGroup 內容Accessing HomeGroup content

重要 APIImportant APIs

存取儲存在使用者 HomeGroup 資料夾中的內容,包括圖片、音樂及視訊。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 中呼叫非同步 API,以了解如何使用 C# 或 Visual Basic 撰寫非同步的 app。You can learn how to write asynchronous apps in C# or Visual Basic, see Call asynchronous APIs in C# or Visual Basic. 若要了解如何使用 C++ 撰寫非同步的 App,請參閱 C++ 的非同步程式設計To learn how to write asynchronous apps in C++, see Asynchronous programming in C++.

  • App 功能宣告App capabilty declarations

    若要存取 HomeGroup 內容,使用者的電腦必須設定 HomeGroup,而且您的 app 必須至少具有下列其中一項功能: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. 當您的 app 存取 HomeGroup 資料夾時,它將只會看到與您在 app 資訊清單中宣告之功能對應的媒體櫃。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.

    注意

     無論應用程式資訊清單中是否宣告了這些功能,或者無論使用者是否使用分享設定,您的應用程式均看不到 HomeGroup 的「文件」媒體櫃中的內容。 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

    您通常會使用檔案選擇器來存取 HomeGroup 中的檔案和資料夾。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

    您可以使用查詢來列舉 HomeGroup 中的檔案和資料夾。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.

在 HomeGroup 開啟檔案選擇器Open the file picker at the HomeGroup

遵循下列步驟開啟檔案選擇器的執行個體,讓使用者從 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. 或者,設定與您的使用者和 app 相關的其他屬性。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

    這個範例會建立在 HomeGroup 開啟的檔案選擇器 (包含任何檔案類型),並以縮圖影像顯示檔案: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.
    }   
    

搜尋 HomeGroup 中的檔案Search the HomeGroup for files

本節示範如何尋找符合使用者查詢字詞的 HomeGroup 項目。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.

    下列範例會在 HomeGroup 中執行搜尋查詢,並將任何相符檔案的名稱儲存為字串清單。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";
        }
    }    
    

搜尋 HomeGroup 中特定使用者的分享檔案Search the HomeGroup for a particular user's shared files

本節說明如何尋找由特定使用者分享的 HomeGroup 檔案。This section shows you how to find HomeGroup files that are shared by a particular user.

  1. 取得 HomeGroup 使用者的集合。Get a collection of HomeGroup users.

    HomeGroup 中的每個第一層資料夾都代表不同的 HomeGroup 使用者。Each of the first-level folders in the HomeGroup represents an individual HomeGroup user. 因此,若要取得 HomeGroup 使用者的集合,請呼叫 GetFoldersAsync 擷取最上層 HomeGroup 資料夾。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";
                }
            }
        }
    }    
    

從 HomeGroup 串流視訊Stream video from the HomeGroup

遵循這些步驟從 HomeGroup 串流視訊內容:Follow these steps to stream video content from the HomeGroup:

  1. 在應用程式中包含 MediaElement。Include a MediaElement in your app.

    MediaElement 可以讓您在 app 中播放音訊和視訊內容。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. 在 HomeGroup 開啟檔案選擇器,套用包含您應用程式所支援格式之視訊檔案的篩選。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.
    }