程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> 關於.NET >> Windows 8 Store Apps學習(22) 文件系統: 訪問文件夾和文件,搜索本地文件

Windows 8 Store Apps學習(22) 文件系統: 訪問文件夾和文件,搜索本地文件

編輯:關於.NET

文件系統: 訪問文件夾和文件, 通過 AQS 搜索本地文件

介紹

重新想象 Windows 8 Store Apps 之 文件系統

File Access - 訪問文件夾和文件,以及獲取文件的各種屬性

Folder Access - 遍歷文件夾時的一些特殊操作

Thumbnail Access - 獲取文件的縮略圖

AQS - 通過 AQS(Advanced Query Syntax)搜索本地文件

示例

1、演示如何訪問文件夾和文件,以及如何獲取文件的各種屬性

FileSystem/FileAccess.xaml

<Page
    x:Class="XamlDemo.FileSystem.FileAccess"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:XamlDemo.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="120 0 0 0">
    
            <TextBlock Name="lblMsg" FontSize="14.667" />
             
            <ListBox Name="listBox" Width="400" Height="200" SelectionChanged="listBox_SelectionChanged_1" HorizontalAlignment="Left" Margin="0 10 0 0" />
                
        </StackPanel>
    </Grid>
</Page>

FileSystem/FileAccess.xaml.cs

/*
 * 演示如何訪問文件夾和文件,以及如何獲取文件的各種屬性
 * 
 * StorageFolder - 文件夾操作類
 *     獲取文件夾相關屬性、重命名、Create...、Get...等
 * 
 * StorageFile - 文件操作類
 *     獲取文件相關屬性、重命名、Create...、Get...、Copy...、Move...、Delete...、Open...、

Replace...等
 *     
 * 注:WinRT 中的關於存儲操作的相關類都在 Windows.Storage 命名空間內
 */
    
using System;
using System.Collections.Generic;
using Windows.Storage;
using Windows.Storage.FileProperties;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using System.Linq;
    
namespace XamlDemo.FileSystem
{
    public sealed partial class FileAccess : Page
    {
        public FileAccess()
        {
            this.InitializeComponent();
        }
    
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            // 遍歷“文檔庫”目錄下的所有頂級文件(需要在 Package.appxmanifest 中選中“文檔庫”功能)
            StorageFolder storageFolder = KnownFolders.DocumentsLibrary;
            IReadOnlyList<StorageFile> files = await storageFolder.GetFilesAsync();
            listBox.ItemsSource = files.Select(p => p.Name).ToList();
        }
    
        private async void listBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
            // 獲取用戶選中的文件
            string fileName = (string)listBox.SelectedItem;
            StorageFolder storageFolder = KnownFolders.DocumentsLibrary;
            StorageFile storageFile = await storageFolder.GetFileAsync(fileName);
    
            // 顯示文件的各種屬性
            if (storageFile != null)
            {
                lblMsg.Text = "Name:" + storageFile.Name;
                lblMsg.Text += Environment.NewLine;
                lblMsg.Text += "FileType:" + storageFile.FileType;
                lblMsg.Text += Environment.NewLine;
    
                BasicProperties basicProperties = await storageFile.GetBasicPropertiesAsync();
                lblMsg.Text += "Size:" + basicProperties.Size;
                lblMsg.Text += Environment.NewLine;
                lblMsg.Text += "DateModified:" + basicProperties.DateModified;
                lblMsg.Text += Environment.NewLine;
    
                /*
                 * 獲取文件的其它各種屬性
                 * 詳細屬性列表請參見:http://msdn.microsoft.com/en-us/library/windows/desktop/ff521735(v=vs.85).aspx
                 */
                List<string> propertiesName = new List<string>();
                propertiesName.Add("System.DateAccessed");
                propertiesName.Add("System.DateCreated");
                propertiesName.Add("System.FileOwner");
                IDictionary<string, object> extraProperties = await storageFile.Properties.RetrievePropertiesAsync(propertiesName);
    
                lblMsg.Text += "System.DateAccessed:" + extraProperties["System.DateAccessed"];
                lblMsg.Text += Environment.NewLine;
                lblMsg.Text += "System.DateCreated:" + extraProperties["System.DateCreated"];
                lblMsg.Text += Environment.NewLine;
                lblMsg.Text += "System.FileOwner:" + extraProperties["System.FileOwner"];
            }
        }
    }
}

2、演示遍歷文件夾時的一些特殊操作

FileSystem/FolderAccess.xaml

<Page
    x:Class="XamlDemo.FileSystem.FolderAccess"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:XamlDemo.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="120 0 0 0">
    
            <TextBlock Name="lblMsg" FontSize="14.667" />
    
            <Button Name="btnGroupFile" Content="分組文件" Click="btnGroupFile_Click_1" Margin="0 10 0 0" />
    
            <Button Name="btnPrefetchAPI" Content="從 Prefetch 中加載信息" Click="btnPrefetchAPI_Click_1" Margin="0 10 0 0" />
                
        </StackPanel>
    </Grid>
</Page>

FileSystem/FolderAccess.xaml.cs

/*
 * 演示遍歷文件夾時的一些特殊操作
 * 1、演示如何對 StorageFolder 中的內容做分組
 * 2、演示如何通過文件擴展名過濾內容,以及如何從 Prefetch 中獲取數據
 * 
 * StorageFolder - 文件夾操作類
 *     獲取文件夾相關屬性、重命名、Create...、Get...等
 * 
 * StorageFile - 文件操作類
 *     獲取文件相關屬性、重命名、Create...、Get...、Copy...、Move...、Delete...、Open...、

Replace...等
 *     
 * 注:WinRT 中的關於存儲操作的相關類都在 Windows.Storage 命名空間內
 */
    
using System;
using System.Collections.Generic;
using Windows.Storage;
using Windows.Storage.FileProperties;
using Windows.Storage.Search;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
    
namespace XamlDemo.FileSystem
{
    public sealed partial class FolderAccess : Page
    {
        public FolderAccess()
        {
            this.InitializeComponent();
        }
    
        // 演示如何對 StorageFolder 中的內容做分組
        private async void btnGroupFile_Click_1(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            lblMsg.Text = "";
    
            StorageFolder picturesFolder = KnownFolders.PicturesLibrary;
    
            // 創建一個按月份分組的查詢
            QueryOptions queryOptions = new QueryOptions(CommonFolderQuery.GroupByMonth);
            // 對指定文件夾執行指定的文件夾查詢,返回分組後的文件夾數據
            StorageFolderQueryResult queryResult = picturesFolder.CreateFolderQueryWithOptions(queryOptions);
    
            IReadOnlyList<StorageFolder> folderList = await queryResult.GetFoldersAsync();
            foreach (StorageFolder folder in folderList) // 這裡的 floder 就是按月份分組後的月份文件夾(當然,物理上並沒有月份文件夾)
            {
                IReadOnlyList<StorageFile> fileList = await folder.GetFilesAsync();
                lblMsg.Text += folder.Name + " (" + fileList.Count + ")";
                lblMsg.Text += Environment.NewLine;
                foreach (StorageFile file in fileList) // 月份文件夾內的文件
                {
                    lblMsg.Text += "    " + file.Name;
                    lblMsg.Text += Environment.NewLine;
                }
            }
        }
    
        // 演示如何通過文件擴展名過濾內容,以及如何從 Prefetch 中獲取數據
        private async void btnPrefetchAPI_Click_1(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            /*
             * Prefetch 是預讀的文件信息,其在 C:\Windows\Prefetch 目錄內,可以從中獲取文件屬性信息和文件縮略圖,在訪問大量文件的場景下可以提高效率
             */
    
            lblMsg.Text = "";
    
            List<string> fileTypeFilter = new List<string>();
            fileTypeFilter.Add(".jpg");
            fileTypeFilter.Add(".png");
    
            // 新建一個查詢,指定需要查詢的文件的擴展名
            QueryOptions queryOptions = new QueryOptions(CommonFileQuery.OrderByName, fileTypeFilter);
    
            // 通過 QueryOptions.SetPropertyPrefetch() 來設置需要從 Prefetch 中獲取的屬性信息
            List<string> propertyNames = new List<string>();
            propertyNames.Add("System.FileOwner");
            queryOptions.SetPropertyPrefetch(PropertyPrefetchOptions.ImageProperties, propertyNames);
    
            /*
             * 通過 QueryOptions.SetThumbnailPrefetch() 來設置需要從 Prefetch 中獲取的縮略圖
               uint requestedSize = 190;
               ThumbnailMode thumbnailMode = ThumbnailMode.PicturesView;
               ThumbnailOptions thumbnailOptions = ThumbnailOptions.UseCurrentScale;
               queryOptions.SetThumbnailPrefetch(thumbnailMode, requestedSize, thumbnailOptions);
            */
    
            // 對指定文件夾執行指定的文件查詢,返回查詢後的文件數據
            StorageFileQueryResult queryResult = KnownFolders.PicturesLibrary.CreateFileQueryWithOptions(queryOptions);
    
            IReadOnlyList<StorageFile> fileList = await queryResult.GetFilesAsync();
            foreach (StorageFile file in fileList)
            {
                lblMsg.Text += file.Name; // 文件名
    
                // 獲取圖像屬性
                ImageProperties properties = await file.Properties.GetImagePropertiesAsync(); 
                lblMsg.Text += "(" + properties.Width + "x" + properties.Height + ")";
    
                // 獲取其他屬性(詳細屬性列表請參見:http://msdn.microsoft.com/en-us/library/windows/desktop/ff521735(v=vs.85).aspx)
                IDictionary<string, object> extraProperties = await file.Properties.RetrievePropertiesAsync(propertyNames);
                lblMsg.Text += "(" + extraProperties["System.FileOwner"] + ")";
                    
                // 獲取縮略圖
                // StorageItemThumbnail thumbnail = await file.GetThumbnailAsync(thumbnailMode, requestedSize, thumbnailOptions);
            }
        }
    }
}

3、演示如何獲取文件的縮略圖

FileSystem/ThumbnailAccess.xaml

<Page
    x:Class="XamlDemo.FileSystem.ThumbnailAccess"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:XamlDemo.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">
       <ScrollViewer Margin="120 0 0 0">
            <StackPanel>
    
                <Button Name="btnGetThumbnail" Content="獲取文件的縮略圖" Click="btnGetThumbnail_Click_1" />
    
                <Image Name="img" Stretch="None" HorizontalAlignment="Left" Margin="0 10 0 0" />
                <TextBlock Name="lblMsg" FontSize="14.667" Margin="0 10 0 0" />
    
            </StackPanel>
        </ScrollViewer>
    </Grid>
</Page>

FileSystem/ThumbnailAccess.xaml.cs

/*
 * 演示如何獲取文件的縮略圖
 * 
 * 獲取指定文件或文件夾的縮略圖,返回 StorageItemThumbnail 類型的數據
 * StorageFile.GetThumbnailAsync(ThumbnailMode mode, uint requestedSize, ThumbnailOptions 

options)
 * StorageFolder.GetThumbnailAsync(ThumbnailMode mode, uint requestedSize, ThumbnailOptions 

options)
 *     ThumbnailMode mode - 用於描述縮略圖的目的,以使系統確定縮略圖圖像的調整方式

(PicturesView, VideosView, MusicView, DocumentsView, ListView, SingleItem)
 *         關於 ThumbnailMode 的詳細介紹參見:http://msdn.microsoft.com/en-

us/library/windows/apps/hh465350.aspx
 *     uint requestedSize - 期望尺寸的最長邊長的大小
 *     ThumbnailOptions options - 檢索和調整縮略圖的行為(None, ReturnOnlyIfCached, 

ResizeThumbnail, UseCurrentScale)
 */
    
using System;
using Windows.Storage;
using Windows.Storage.FileProperties;
using Windows.Storage.Pickers;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Imaging;
    
namespace XamlDemo.FileSystem
{
    public sealed partial class ThumbnailAccess : Page
    {
        public ThumbnailAccess()
        {
            this.InitializeComponent();
        }
    
        private async void btnGetThumbnail_Click_1(object sender, RoutedEventArgs e)
        {
            if (XamlDemo.Common.Helper.EnsureUnsnapped())
            {
                FileOpenPicker openPicker = new FileOpenPicker();
                openPicker.FileTypeFilter.Add("*");
    
                StorageFile file = await openPicker.PickSingleFileAsync();
                if (file != null)
                {   
                    ThumbnailMode thumbnailMode = ThumbnailMode.PicturesView;
                    ThumbnailOptions thumbnailOptions = ThumbnailOptions.UseCurrentScale;
                    uint requestedSize = 200;
    
                    using (StorageItemThumbnail thumbnail = await file.GetThumbnailAsync(thumbnailMode, requestedSize, thumbnailOptions)) 
                    {
                        if (thumbnail != null)
                        {
                            BitmapImage bitmapImage = new BitmapImage();
                            bitmapImage.SetSource(thumbnail);
                            img.Source = bitmapImage;
    
                            lblMsg.Text = "file name: " + file.Name;
                            lblMsg.Text += Environment.NewLine;
                            lblMsg.Text += "requested size: " + requestedSize;
                            lblMsg.Text += Environment.NewLine;
                            lblMsg.Text += "returned size: " + thumbnail.OriginalWidth + "*" + thumbnail.OriginalHeight;
                        }
                    }
                }
            }
        }
    }
}

4、演示如何通過 AQS - Advanced Query Syntax 搜索本地文件

FileSystem/AQS.xaml.cs

/*
 * 演示如何通過 AQS - Advanced Query Syntax 搜索本地文件
 */
    
using System;
using System.Collections.Generic;
using Windows.Storage;
using Windows.Storage.BulkAccess;
using Windows.Storage.FileProperties;
using Windows.Storage.Search;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
    
namespace XamlDemo.FileSystem
{
    public sealed partial class AQS : Page
    {
        public AQS()
        {
            this.InitializeComponent();
        }
    
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            // 准備在“音樂庫”中進行搜索(需要在 Package.appxmanifest 的“功能”中選中“音樂庫”)
            StorageFolder musicFolder = KnownFolders.MusicLibrary;
    
            // 准備搜索所有類型的文件
            List<string> fileTypeFilter = new List<string>();
            fileTypeFilter.Add("*");
    
            // 搜索的查詢參數
            QueryOptions queryOptions = new QueryOptions(CommonFileQuery.OrderByDate, fileTypeFilter);
            // 指定 AQS 字符串,參見 http://msdn.microsoft.com/zh-cn/library/windows/apps/aa965711.aspx
            queryOptions.UserSearchFilter = "五月天";
    
            // 根據指定的參數創建一個查詢
            StorageFileQueryResult fileQuery = musicFolder.CreateFileQueryWithOptions(queryOptions);
    
            lblMsg.Text = "在音樂庫中搜索“五月天”,結果如下:";
            lblMsg.Text += Environment.NewLine;
    
            // 開始搜索,並返回檢索到的文件列表
            IReadOnlyList<StorageFile> files = await fileQuery.GetFilesAsync();
    
            if (files.Count == 0)
            {
                lblMsg.Text += "什麼都沒搜到";
            }
            else
            {
                foreach (StorageFile file in files)
                {
                    lblMsg.Text += file.Name;
                    lblMsg.Text += Environment.NewLine;
                }
            }
    
    
    
            // 關於 QueryOptions 的一些用法,更詳細的 QueryOptions 的說明請參見 msdn
            queryOptions = new QueryOptions();
            queryOptions.FolderDepth = FolderDepth.Deep;
            queryOptions.IndexerOption = IndexerOption.UseIndexerWhenAvailable;
            queryOptions.SortOrder.Clear();
            var sortEntry = new SortEntry();
            sortEntry.PropertyName = "System.FileName";
            sortEntry.AscendingOrder = true;
            queryOptions.SortOrder.Add(sortEntry);
    
            fileQuery = KnownFolders.PicturesLibrary.CreateFileQueryWithOptions(queryOptions);
        }
    }
}

OK

[源碼下載]:http://files.cnblogs.com/webabcd/Windows8.rar

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved