获取文件在windows中显示的图标

2018/4/21 23:51:51


有时候我们可能会需要获取某种类型文件的图标,使用C#可以轻松做到获取windows中显示的文件显示图标。

通过StorageFile.GetThumbnailAsync()获取文件图标,和StorageFolder.GetThumbnailAsync()函数获取文件夹图标。

注意:StorageFile和StorageFolder是UWP才可使用的类,WPF没有该类。此处仅说UWP版

 

具体函数如下:

        /// <summary>
        /// 获取文件或文件夹图标
        /// </summary>
        /// <param name="storageItem"></param>
        /// <returns></returns>
        /// <summary>
        public static async Task<BitmapImage> GetIcon(IStorageItem storageItem)
        {
            BitmapImage bitmapImage = new BitmapImage();
            if (storageItem is StorageFolder)
            {
                using (StorageItemThumbnail storageItemThumbnail = await (storageItem as StorageFolder).GetThumbnailAsync(ThumbnailMode.SingleItem))
                {
                    bitmapImage.SetSource(storageItemThumbnail);
                }
            }
            else if (storageItem is StorageFile)
            {
                using (StorageItemThumbnail storageItemThumbnail = await (storageItem as StorageFile).GetThumbnailAsync(ThumbnailMode.SingleItem))
                {
                    bitmapImage.SetSource(storageItemThumbnail);
                }
            }
            return bitmapImage;
        }

参数storageItem为IStorageItem接口,StorageFile和StorageFolder实现了此接口,因此该函数可返回文件或文件夹的图标。使用此函数时,可传入StorageFile或StorageFolder。

GetThumbnailAsync()返回值类型为StorageItemThumbnail,应在获取图标后立即注销该对象,以释放内存,所以将其放入Using块中即可。

另附上Encipher使用此函数实现的获取图标显示:

Encipher截屏