1. 程式人生 > >背水一戰 Windows 10 (87) - 文件系統: 獲取文件的屬性, 修改文件的屬性, 獲取文件的縮略圖

背水一戰 Windows 10 (87) - 文件系統: 獲取文件的屬性, 修改文件的屬性, 獲取文件的縮略圖

esc spl () protect nbsp mob classType log location

[源碼下載]


背水一戰 Windows 10 (87) - 文件系統: 獲取文件的屬性, 修改文件的屬性, 獲取文件的縮略圖



作者:webabcd


介紹
背水一戰 Windows 10 之 文件系統

  • 獲取文件的屬性
  • 修改文件的屬性
  • 獲取文件的縮略圖



示例
1、演示如何獲取文件的屬性,修改文件的屬性
FileSystem/FileProperties.xaml

<Page
    x:Class="Windows10.FileSystem.FileProperties"
    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"> <ListBox Name="listBox" Width="400" Height="200" HorizontalAlignment="Left" Margin="5" SelectionChanged="listBox_SelectionChanged" /> <Button Name="btnModifyProperty" Content="修改文件的屬性" Margin="5" Click="btnModifyProperty_Click" /> <
TextBlock Name="lblMsg" Margin="5" /> </StackPanel> </Grid> </Page>

FileSystem/FileProperties.xaml.cs

/*
 * 演示如何獲取文件的屬性,修改文件的屬性
 * 
 * StorageFile - 文件操作類
 *     直接通過調用 Name, Path, DisplayName, DisplayType, FolderRelativeId, Provider, DateCreated, Attributes, ContentType, FileType, IsAvailable 獲取相關屬性,詳見文檔
 *     GetBasicPropertiesAsync() - 返回一個 BasicProperties 類型的對象 
 *     Properties - 返回一個 StorageItemContentProperties 類型的對象
 *
 * BasicProperties
 *     可以獲取的數據有 Size, DateModified, ItemDate
 * 
 * StorageItemContentProperties
 *     通過 GetImagePropertiesAsync() 獲取圖片屬性,詳見文檔
 *     通過 GetVideoPropertiesAsync() 獲取視頻屬性,詳見文檔
 *     通過 GetMusicPropertiesAsync() 獲取音頻屬性,詳見文檔
 *     通過 GetDocumentPropertiesAsync() 獲取文檔屬性,詳見文檔
 *     通過調用 RetrievePropertiesAsync() 方法來獲取指定的屬性,然後可以調用 SavePropertiesAsync() 方法來保存修改後的屬性,詳見下面的示例
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.Storage.FileProperties;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

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

        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            // 獲取“圖片庫”目錄下的所有根文件
            StorageFolder picturesFolder = await KnownFolders.GetFolderForUserAsync(null, KnownFolderId.PicturesLibrary);
            IReadOnlyList<StorageFile> fileList = await picturesFolder.GetFilesAsync();
            listBox.ItemsSource = fileList.Select(p => p.Name).ToList();

            base.OnNavigatedTo(e);
        }

        private async void listBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // 用戶選中的文件
            string fileName = (string)listBox.SelectedItem;
            StorageFolder picturesFolder = await KnownFolders.GetFolderForUserAsync(null, KnownFolderId.PicturesLibrary);
            StorageFile storageFile = await picturesFolder.GetFileAsync(fileName);

            // 顯示文件的各種屬性
            ShowProperties1(storageFile);
            await ShowProperties2(storageFile);
            await ShowProperties3(storageFile);
            await ShowProperties4(storageFile);
        }

        // 通過 StorageFile 獲取文件的屬性
        private void ShowProperties1(StorageFile storageFile)
        {
            lblMsg.Text = "Name:" + storageFile.Name;
            lblMsg.Text += Environment.NewLine;
            lblMsg.Text += "Path:" + storageFile.Path;
            lblMsg.Text += Environment.NewLine;
            lblMsg.Text += "DisplayName:" + storageFile.DisplayName;
            lblMsg.Text += Environment.NewLine;
            lblMsg.Text += "DisplayType:" + storageFile.DisplayType;
            lblMsg.Text += Environment.NewLine;
            lblMsg.Text += "FolderRelativeId:" + storageFile.FolderRelativeId;
            lblMsg.Text += Environment.NewLine;
            lblMsg.Text += "Provider:" + storageFile.Provider;
            lblMsg.Text += Environment.NewLine;
            lblMsg.Text += "DateCreated:" + storageFile.DateCreated;
            lblMsg.Text += Environment.NewLine;
            lblMsg.Text += "Attributes:" + storageFile.Attributes; // 返回一個 FileAttributes 類型的枚舉(FlagsAttribute),可以從中獲知文件是否是 ReadOnly 之類的信息
            lblMsg.Text += Environment.NewLine;
            lblMsg.Text += "ContentType:" + storageFile.ContentType;
            lblMsg.Text += Environment.NewLine;
            lblMsg.Text += "FileType:" + storageFile.FileType;
            lblMsg.Text += Environment.NewLine;
            lblMsg.Text += "IsAvailable:" + storageFile.IsAvailable;
            lblMsg.Text += Environment.NewLine;
        }

        // 通過 StorageFile.GetBasicPropertiesAsync() 獲取文件的屬性
        private async Task ShowProperties2(StorageFile storageFile)
        {
            BasicProperties basicProperties = await storageFile.GetBasicPropertiesAsync();
            lblMsg.Text += "Size:" + basicProperties.Size;
            lblMsg.Text += Environment.NewLine;
            lblMsg.Text += "DateModified:" + basicProperties.DateModified;
            lblMsg.Text += Environment.NewLine;
            lblMsg.Text += "ItemDate:" + basicProperties.ItemDate;
            lblMsg.Text += Environment.NewLine;
        }

        // 通過 StorageFolder.Properties 的 RetrievePropertiesAsync() 方法獲取文件的屬性
        private async Task ShowProperties3(StorageFile storageFile)
        {
            /*
             * 獲取文件的其它各種屬性
             * 詳細的屬性列表請參見結尾處的“附錄一: 屬性列表”或者參見: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");
            propertiesName.Add("System.FileAttributes");

            StorageItemContentProperties storageItemContentProperties = storageFile.Properties;
            IDictionary<string, object> extraProperties = await storageItemContentProperties.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"];
            lblMsg.Text += Environment.NewLine;
            lblMsg.Text += "System.FileAttributes:" + extraProperties["System.FileAttributes"];
            lblMsg.Text += Environment.NewLine;
        }

        // 通過 StorageFolder.Properties 的 GetImagePropertiesAsync(), GetVideoPropertiesAsync(), GetMusicPropertiesAsync(), GetDocumentPropertiesAsync() 方法獲取文件的屬性
        private async Task ShowProperties4(StorageFile storageFile)
        {
            StorageItemContentProperties storageItemContentProperties = storageFile.Properties;
            ImageProperties imageProperties = await storageItemContentProperties.GetImagePropertiesAsync(); // 圖片屬性
            VideoProperties videoProperties = await storageItemContentProperties.GetVideoPropertiesAsync(); // 視頻屬性
            MusicProperties musicProperties = await storageItemContentProperties.GetMusicPropertiesAsync(); // 音頻屬性
            DocumentProperties documentProperties = await storageItemContentProperties.GetDocumentPropertiesAsync(); // 文檔屬性

            lblMsg.Text += "image width:" + imageProperties.Width;
            lblMsg.Text += Environment.NewLine;
            lblMsg.Text += "image height:" + imageProperties.Height;
            lblMsg.Text += Environment.NewLine;
        }

        // 修改文件的屬性
        private async void btnModifyProperty_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            // 用戶選中的文件
            string fileName = (string)listBox.SelectedItem;
            StorageFolder picturesFolder = await KnownFolders.GetFolderForUserAsync(null, KnownFolderId.PicturesLibrary);
            StorageFile storageFile = await picturesFolder.GetFileAsync(fileName);

            // 在 System.FileAttributes 中保存有文件是否是“只讀”的信息
            string[] retrieveList = new string[] { "System.FileAttributes" };
            StorageItemContentProperties storageItemContentProperties = storageFile.Properties;
            IDictionary<string, object> extraProperties = await storageItemContentProperties.RetrievePropertiesAsync(retrieveList);

            uint FILE_ATTRIBUTES_READONLY = 1;
            if (extraProperties != null && extraProperties.ContainsKey("System.FileAttributes"))
            {
                // 切換文件的只讀屬性
                uint temp = (UInt32)extraProperties["System.FileAttributes"] ^ FILE_ATTRIBUTES_READONLY;

                // 設置文件的只讀屬性為 true
                // uint temp = (UInt32)extraProperties["System.FileAttributes"] | 1;

                // 設置文件的只讀屬性為 false
                // uint temp = (UInt32)extraProperties["System.FileAttributes"] & 0;

                extraProperties["System.FileAttributes"] = temp;
            }
            else
            {
                // 設置文件的只讀屬性為 true
                extraProperties = new PropertySet();
                extraProperties.Add("System.FileAttributes", FILE_ATTRIBUTES_READONLY);
            }

            // 保存修改後的屬性(用這種方法可以修改部分屬性,大部分屬性都是無權限修改的)
            await storageFile.Properties.SavePropertiesAsync(extraProperties);
        }
    }
}


/*
----------------------------------------------------------------------
附錄一: 屬性列表

System.AcquisitionID
System.ApplicationName
System.Author
System.Capacity
System.Category
System.Comment
System.Company
System.ComputerName
System.ContainedItems
System.ContentStatus
System.ContentType
System.Copyright
System.DataObjectFormat
System.DateAccessed
System.DateAcquired
System.DateArchived
System.DateCompleted
System.DateCreated
System.DateImported
System.DateModified
System.DefaultSaveLocationIconDisplay
System.DueDate
System.EndDate
System.FileAllocationSize
System.FileAttributes
System.FileCount
System.FileDescription
System.FileExtension
System.FileFRN
System.FileName
System.FileOwner
System.FileVersion
System.FindData
System.FlagColor
System.FlagColorText
System.FlagStatus
System.FlagStatusText
System.FreeSpace
System.FullText
System.Identity
System.Identity.Blob
System.Identity.DisplayName
System.Identity.IsMeIdentity
System.Identity.PrimaryEmailAddress
System.Identity.ProviderID
System.Identity.UniqueID
System.Identity.UserName
System.IdentityProvider.Name
System.IdentityProvider.Picture
System.ImageParsingName
System.Importance
System.ImportanceText
System.IsAttachment
System.IsDefaultNonOwnerSaveLocation
System.IsDefaultSaveLocation
System.IsDeleted
System.IsEncrypted
System.IsFlagged
System.IsFlaggedComplete
System.IsIncomplete
System.IsLocationSupported
System.IsPinnedToNameSpaceTree
System.IsRead
System.IsSearchOnlyItem
System.IsSendToTarget
System.IsShared
System.ItemAuthors
System.ItemClassType
System.ItemDate
System.ItemFolderNameDisplay
System.ItemFolderPathDisplay
System.ItemFolderPathDisplayNarrow
System.ItemName
System.ItemNameDisplay
System.ItemNamePrefix
System.ItemParticipants
System.ItemPathDisplay
System.ItemPathDisplayNarrow
System.ItemType
System.ItemTypeText
System.ItemUrl
System.Keywords
System.Kind
System.KindText
System.Language
System.LayoutPattern.ContentViewModeForBrowse
System.LayoutPattern.ContentViewModeForSearch
System.LibraryLocationsCount
System.MileageInformation
System.MIMEType
System.Null
System.OfflineAvailability
System.OfflineStatus
System.OriginalFileName
System.OwnerSID
System.ParentalRating
System.ParentalRatingReason
System.ParentalRatingsOrganization
System.ParsingBindContext
System.ParsingName
System.ParsingPath
System.PerceivedType
System.PercentFull
System.Priority
System.PriorityText
System.Project
System.ProviderItemID
System.Rating
System.RatingText
System.Sensitivity
System.SensitivityText
System.SFGAOFlags
System.SharedWith
System.ShareUserRating
System.SharingStatus
System.Shell.OmitFromView
System.SimpleRating
System.Size
System.SoftwareUsed
System.SourceItem
System.StartDate
System.Status
System.StatusBarSelectedItemCount
System.StatusBarViewItemCount
System.Subject
System.Thumbnail
System.ThumbnailCacheId
System.ThumbnailStream
System.Title
System.TotalFileSize
System.Trademarks
----------------------------------------------------------------------
*/


2、演示如何獲取文件的縮略圖
FileSystem/FileThumbnail.xaml

<Page
    x:Class="Windows10.FileSystem.FileThumbnail"
    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" />

            <ListBox Name="listBox" Width="400" Height="200" HorizontalAlignment="Left" Margin="5" SelectionChanged="listBox_SelectionChanged" />

            <Image Name="imageThumbnail" Stretch="None" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="5" />

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

FileSystem/FileThumbnail.xaml.cs

/*
 * 演示如何獲取文件的縮略圖
 * 
 * StorageFile - 文件操作類。與獲取文件縮略圖相關的接口如下
 *     public IAsyncOperation<StorageItemThumbnail> GetThumbnailAsync(ThumbnailMode mode);
 *     public IAsyncOperation<StorageItemThumbnail> GetThumbnailAsync(ThumbnailMode mode, uint requestedSize);
 *     public IAsyncOperation<StorageItemThumbnail> GetThumbnailAsync(ThumbnailMode mode, uint requestedSize, ThumbnailOptions options);
 *         ThumbnailMode mode - 用於描述縮略圖的目的,以使系統確定縮略圖圖像的調整方式(就用 SingleItem 即可)
 *         uint requestedSize - 期望尺寸的最長邊長的大小
 *         ThumbnailOptions options - 檢索和調整縮略圖的行為(默認值:UseCurrentScale)
 *         
 * StorageItemThumbnail - 縮略圖(實現了 IRandomAccessStream 接口,可以直接轉換為 BitmapImage 對象)
 *     OriginalWidth - 縮略圖的寬
 *     OriginalHeight - 縮略圖的高
 *     Size - 縮略圖的大小(單位:字節)
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.Storage.FileProperties;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;

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

        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            // 獲取“圖片庫”目錄下的所有根文件
            StorageFolder picturesFolder = await KnownFolders.GetFolderForUserAsync(null, KnownFolderId.PicturesLibrary);
            IReadOnlyList<StorageFile> fileList = await picturesFolder.GetFilesAsync();
            listBox.ItemsSource = fileList.Select(p => p.Name).ToList();

            base.OnNavigatedTo(e);
        }

        private async void listBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // 用戶選中的文件
            string fileName = (string)listBox.SelectedItem;
            StorageFolder picturesFolder = await KnownFolders.GetFolderForUserAsync(null, KnownFolderId.PicturesLibrary);
            StorageFile storageFile = await picturesFolder.GetFileAsync(fileName);

            // 顯示文件的縮略圖
            await ShowThumbnail(storageFile);
        }

        private async Task ShowThumbnail(StorageFile storageFile)
        {
            // 如果要獲取文件的縮略圖,就指定為 ThumbnailMode.SingleItem 即可
            ThumbnailMode thumbnailMode = ThumbnailMode.SingleItem;
            uint requestedSize = 200;
            ThumbnailOptions thumbnailOptions = ThumbnailOptions.UseCurrentScale;

            using (StorageItemThumbnail thumbnail = await storageFile.GetThumbnailAsync(thumbnailMode, requestedSize, thumbnailOptions))
            {
                if (thumbnail != null)
                {
                    BitmapImage bitmapImage = new BitmapImage();
                    bitmapImage.SetSource(thumbnail);
                    imageThumbnail.Source = bitmapImage;

                    lblMsg.Text = $"thumbnail1 requestedSize:{requestedSize}, returnedSize:{thumbnail.OriginalWidth}x{thumbnail.OriginalHeight}, size:{thumbnail.Size}";
                }
            }
        }
    }
}



OK
[源碼下載]

FilePropertiesFileSystem/FileProperties.xamlFileSystem/FileProperties.xamlFileSystem/FileProperties.xamlFileSystem/FileProperties.xamlFileSystem/FileProperties.xamlFileSystem/FileProperties.xamlFileSystem/FileProperties.xamlFileSystem/FileProperties.xaml

背水一戰 Windows 10 (87) - 文件系統: 獲取文件的屬性, 修改文件的屬性, 獲取文件的縮略圖