背水一战 Windows 10 (92) - 文件系统: 读写“最近访问列表”和“未来访问列表”, 管理以及使用索引

[源码下载]


背水一战 Windows 10 (92) - 文件系统: 读写“最近访问列表”和“未来访问列表”, 管理以及使用索引



作者:webabcd


介绍
背水一战 Windows 10 之 文件系统

  • 读写“最近访问列表”和“未来访问列表”
  • 管理以及使用索



示例
1、演示如何读写“最近访问列表”和“未来访问列表”
FileSystem/Token/TokenDemo.xaml

<Page
    x:Class="Windows10.FileSystem.TokenDemo"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Windows10.FileSystem"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="Transparent">
        <StackPanel Margin="10 0 10 10">

            <TextBlock Name="lblMsg" Margin="5" />

            <Button Name="btnAddToMostRecentlyUsedList" Content="AddToMostRecentlyUsedList" Click="btnAddToMostRecentlyUsedList_Click" Margin="5" />

            <Button Name="btnGetMostRecentlyUsedList" Content="GetMostRecentlyUsedList" Click="btnGetMostRecentlyUsedList_Click" Margin="5" />

            <Button Name="btnAddToFutureAccessList" Content="AddToFutureAccessList" Click="btnAddToFutureAccessList_Click" Margin="5" />

            <Button Name="btnGetFutureAccessList" Content="GetFutureAccessList" Click="btnGetFutureAccessList_Click" Margin="5" />

        </StackPanel>
    </Grid>
</Page>

FileSystem/Token/TokenDemo.xaml.cs

/*
 * 演示如何读写“最近访问列表”和“未来访问列表”
 * 
 * StorageApplicationPermissions - 文件/文件夹的访问列表
 *     MostRecentlyUsedList - 最近访问列表(实现了 IStorageItemAccessList 接口)
 *     FutureAccessList - 未来访问列表(实现了 IStorageItemAccessList 接口)
 *     IStorageItemAccessList
 *         Add(IStorageItem file, string metadata) - 添加文件或文件夹到“列表”,返回 token 值(一个字符串类型的标识),通过此值可以方便地检索到对应的文件或文件夹
 *             file - 需要添加到列表的文件或文件夹
 *             metadata - 自定义元数据,相当于上下文
 *         AddOrReplace(string token, IStorageItem file, string metadata) - 添加文件或文件夹到“列表”,如果已存在则替换
 *         GetFileAsync(string token) - 根据 token 值,在“列表”查找对应的文件
 *         GetFolderAsync(string token) - 根据 token 值,在“列表”查找对应的文件夹
 *         GetItemAsync(string token) - 根据 token 值,在“列表”查找对应的文件或文件夹
 *         Remove(string token) - 从“列表”中删除指定 token 值的文件或文件夹
 *         ContainsItem(string token) - “列表”中是否存储指定 token 值的文件或文件夹
 *         Clear() - 清除“列表”中的全部文件和文件夹
 *         CheckAccess(IStorageItem file) - 用于验证 app 是否可在“列表”中访问指定的文件或文件夹
 *         Entries - 返回 AccessListEntryView 类型的数据,其是 AccessListEntry 类型数据的集合
 *         MaximumItemsAllowed - “列表”可以保存的文件和文件夹的最大数目
 *         
 * AccessListEntry - 用于封装访问列表中的 StorageFile 或 StorageFolder 的 token 和元数据
 *     Token - token 值
 *     Metadata - 元数据
 *     
 *     
 * 注:
 * 1、通常情况下,MostRecentlyUsedList 最大可以保存 25 条数据,FutureAccessList 最大可以保存 1000 条数据。实际情况可通过 IStorageItemAccessList 的 MaximumItemsAllowed 来获取
 * 2、这个特性的好处就是:保存到 MostRecentlyUsedList 或 FutureAccessList 中的文件或文件夹,可以直接通过 token 访问到
 */

using System;
using Windows.Storage;
using Windows.Storage.AccessCache;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace Windows10.FileSystem
{
    public sealed partial class TokenDemo : Page
    {
        public TokenDemo()
        {
            this.InitializeComponent();
        }

        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            // 在指定的目录下创建指定的文件
            StorageFolder documentsFolder = await KnownFolders.GetFolderForUserAsync(null, KnownFolderId.DocumentsLibrary);
            StorageFile storageFile = await documentsFolder.CreateFileAsync("webabcdCacheAccess.txt", CreationCollisionOption.ReplaceExisting);

            // 在指定的文件中写入指定的文本
            string textContent = "I am webabcd";
            await FileIO.WriteTextAsync(storageFile, textContent, Windows.Storage.Streams.UnicodeEncoding.Utf8);

            base.OnNavigatedTo(e);
        }


        private async void btnAddToMostRecentlyUsedList_Click(object sender, RoutedEventArgs e)
        {
            // 获取文件对象
            StorageFolder documentsFolder = await KnownFolders.GetFolderForUserAsync(null, KnownFolderId.DocumentsLibrary);
            StorageFile storageFile = await documentsFolder.GetFileAsync("webabcdCacheAccess.txt");

            if (storageFile != null && StorageApplicationPermissions.MostRecentlyUsedList.CheckAccess(storageFile))
            {
                // 将文件添加到“最近访问列表”,并获取对应的 token 值
                string token = StorageApplicationPermissions.MostRecentlyUsedList.Add(storageFile, storageFile.Name);
                lblMsg.Text = "token:" + token;
                lblMsg.Text += Environment.NewLine;
                lblMsg.Text += "MostRecentlyUsedList MaximumItemsAllowed: " + StorageApplicationPermissions.MostRecentlyUsedList.MaximumItemsAllowed;
            }
        }

        private async void btnGetMostRecentlyUsedList_Click(object sender, RoutedEventArgs e)
        {
            AccessListEntryView entries = StorageApplicationPermissions.MostRecentlyUsedList.Entries;
            if (entries.Count > 0)
            {
                // 通过 token 值,从“最近访问列表”中获取文件对象
                AccessListEntry entry = entries[0];
                StorageFile storageFile = await StorageApplicationPermissions.MostRecentlyUsedList.GetFileAsync(entry.Token);

                string textContent = await FileIO.ReadTextAsync(storageFile);
                lblMsg.Text = "MostRecentlyUsedList 的第一个文件的文本内容:" + textContent;
            }
            else
            {
                lblMsg.Text = "最近访问列表中无数据";
            }
        }


        private async void btnAddToFutureAccessList_Click(object sender, RoutedEventArgs e)
        {
            // 获取文件对象
            StorageFolder documentsFolder = await KnownFolders.GetFolderForUserAsync(null, KnownFolderId.DocumentsLibrary);
            StorageFile storageFile = await documentsFolder.GetFileAsync("webabcdCacheAccess.txt");

            if (storageFile != null && StorageApplicationPermissions.FutureAccessList.CheckAccess(storageFile))
            {
                // 将文件添加到“未来访问列表”,并获取对应的 token 值
                string token = StorageApplicationPermissions.FutureAccessList.Add(storageFile, storageFile.Name);
                lblMsg.Text = "token:" + token;
                lblMsg.Text += Environment.NewLine;
                lblMsg.Text += "FutureAccessList MaximumItemsAllowed: " + StorageApplicationPermissions.FutureAccessList.MaximumItemsAllowed;
            }
        }
        
        private async void btnGetFutureAccessList_Click(object sender, RoutedEventArgs e)
        {
            AccessListEntryView entries = StorageApplicationPermissions.FutureAccessList.Entries;
            if (entries.Count > 0)
            {
                // 通过 token 值,从“未来访问列表”中获取文件对象
                AccessListEntry entry = entries[0];
                StorageFile storageFile = await StorageApplicationPermissions.FutureAccessList.GetFileAsync(entry.Token);

                string textContent = await FileIO.ReadTextAsync(storageFile);
                lblMsg.Text = "FutureAccessList 的第一个文件的文本内容:" + textContent;
            }
            else
            {
                lblMsg.Text = "未来访问列表中无数据";
            }
        }
    }
}


2、演示如何管理索引器,以及如何通过索引器获取数据
FileSystem/Indexer/IndexerDemo.xaml

<Page
    x:Class="Windows10.FileSystem.Indexer.IndexerDemo"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Windows10.FileSystem.Indexer"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="Transparent">

        <StackPanel Margin="10 0 10 10">

            <Button Name="btnAddToIndexer" Content="添加数据到索引器" Click="btnAddToIndexer_Click" Margin="5" />

            <Button Name="btnRetrieveAllItems" Content="获取索引器中的全部数据" Click="btnRetrieveAllItems_Click" Margin="5" />

            <Button Name="btnRetrieveMatchingItems" Content="按指定的查询条件获取索引器中的数据" Click="btnRetrieveMatchingItems_Click" Margin="5" />

            <ScrollViewer Margin="5" Width="300" Height="400" HorizontalAlignment="Left">
                <TextBlock Name="lblMsg"/>
            </ScrollViewer>

        </StackPanel>
    </Grid>
</Page>

FileSystem/Indexer/IndexerDemo.xaml.cs

/*
 * 演示如何管理索引器,以及如何通过索引器获取数据
 * 
 * ContentIndexer - 索引器管理类
 */

using System;
using System.Collections.Generic;
using Windows.Storage;
using Windows.Storage.Search;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace Windows10.FileSystem.Indexer
{
    public sealed partial class IndexerDemo : Page
    {
        public IndexerDemo()
        {
            this.InitializeComponent();
        }

        // 添加数据到索引器
        private async void btnAddToIndexer_Click(object sender, RoutedEventArgs e)
        {
            // 获取一个索引器(可以指定索引器的名字,从而达到对索引器分类的目的)
            var indexer = ContentIndexer.GetIndexer();
            var content = new IndexableContent();
            for (int i = 0; i < 100; i++)
            {
                content.Properties[SystemProperties.Title] = "Title: " + i.ToString().PadLeft(2, '0');
                content.Properties[SystemProperties.Keywords] = "Keywords: " + i.ToString().PadLeft(2, '0'); // 多个用“;”隔开
                content.Properties[SystemProperties.Comment] = "Comment: " + i.ToString().PadLeft(2, '0');
                content.Id = "key" + i; // 标识,增加同标识的索引就是更新

                // 增加一个索引(另外还有 Update 和 Delete 操作)
                await indexer.AddAsync(content);
            }
        }

        // 获取索引器中的全部数据
        private void btnRetrieveAllItems_Click(object sender, RoutedEventArgs e)
        {
            ExecuteQueryHelper("*");
        }

        // 按指定的查询条件获取索引器中的数据
        private void btnRetrieveMatchingItems_Click(object sender, RoutedEventArgs e)
        {
            ExecuteQueryHelper("title:\"99\"");
        }


        // 按指定的 AQS 语法从索引器中查询数据
        private async void ExecuteQueryHelper(string queryString)
        {
            lblMsg.Text = "";
            var indexer = ContentIndexer.GetIndexer();

            // 需要检索的属性
            string[] propertyKeys =
            {
                SystemProperties.Title,
                SystemProperties.Keywords,
                SystemProperties.Comment
            };
            // 指定 AQS 字符串(Advanced Query Syntax),参见 http://msdn.microsoft.com/zh-cn/library/windows/apps/aa965711.aspx
            var query = indexer.CreateQuery(queryString, propertyKeys);

            // 执行查询,并获取结果
            var documents = await query.GetAsync();
            foreach (var document in documents)
            {
                string itemString = "Key: " + document.Id + "\n";
                foreach (var propertyKey in propertyKeys)
                {
                    itemString += propertyKey + ": " + StringifyProperty(document.Properties[propertyKey]) + "\n";
                }
                lblMsg.Text += itemString + "\n";
            }
        }

        // 如果对象是一个字符串集合则用“;”做分隔符,然后以字符串形式输出
        public string StringifyProperty(object property)
        {
            string propertyString = "";
            if (property != null)
            {
                var vectorProperty = property as IEnumerable<string>;
                if (vectorProperty != null)
                {
                    foreach (var prop in vectorProperty)
                    {
                        propertyString += prop + "; ";
                    }
                }
                else
                {
                    propertyString = property.ToString();
                }
            }
            return propertyString;
        }
    }
}



OK
[源码下载]

posted @ 2018-06-14 09:09  webabcd  阅读(961)  评论(0编辑  收藏  举报