当前位置:  编程技术>.net/c#/asp.net

c#根据文件类型获取相关类型图标的方法代码

    来源: 互联网  发布时间:2014-10-19

    本文导语:  代码如下:using System;using System.Collections.Generic;using System.Text;namespace WindowsFormsApplication1{    using System;    using System.Drawing;    using System.Runtime.InteropServices;    using Microsoft.Win32;    using System.Reflection;    using System.Collections.G...

代码如下:

using System;
using System.Collections.Generic;
using System.Text;

namespace WindowsFormsApplication1
{
    using System;
    using System.Drawing;
    using System.Runtime.InteropServices;
    using Microsoft.Win32;
    using System.Reflection;
    using System.Collections.Generic;

    namespace BlackFox.Win32
    {
        public static class Icons
        {
            #region Custom exceptions class

            public class IconNotFoundException : Exception
            {
                public IconNotFoundException(string fileName, int index)
                    : base(string.Format("Icon with Id = {0} wasn't found in file {1}", index, fileName))
                {
                }
            }

            public class UnableToExtractIconsException : Exception
            {
                public UnableToExtractIconsException(string fileName, int firstIconIndex, int iconCount)
                    : base(string.Format("Tryed to extract {2} icons starting from the one with id {1} from the "{0}" file but failed", fileName, firstIconIndex, iconCount))
                {
                }
            }

            #endregion

            #region DllImports

            ///
            /// Contains information about a file object.
            ///
            struct SHFILEINFO
            {
                ///
                /// Handle to the icon that represents the file. You are responsible for
                /// destroying this handle with DestroyIcon when you no longer need it.
                ///
                public IntPtr hIcon;

                ///
                /// Index of the icon image within the system image list.
                ///
                public IntPtr iIcon;

                ///
                /// Array of values that indicates the attributes of the file object.
                /// For information about these values, see the IShellFolder::GetAttributesOf
                /// method.
                ///
                public uint dwAttributes;

                ///
                /// String that contains the name of the file as it appears in the Microsoft
                /// Windows Shell, or the path and file name of the file that contains the
                /// icon representing the file.
                ///
                [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
                public string szDisplayName;

                ///
                /// String that describes the type of file.
                ///
                [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
                public string szTypeName;
            };

            [Flags]
            enum FileInfoFlags : int
            {
                ///
                /// Retrieve the handle to the icon that represents the file and the index
                /// of the icon within the system image list. The handle is copied to the
                /// hIcon member of the structure specified by psfi, and the index is copied
                /// to the iIcon member.
                ///
                SHGFI_ICON = 0x000000100,
                ///
                /// Indicates that the function should not attempt to access the file
                /// specified by pszPath. Rather, it should act as if the file specified by
                /// pszPath exists with the file attributes passed in dwFileAttributes.
                ///
                SHGFI_USEFILEATTRIBUTES = 0x000000010
            }

            ///
            ///     Creates an array of handles to large or small icons extracted from
            ///     the specified executable file, dynamic-link library (DLL), or icon
            ///     file.
            ///
            ///
            ///     Name of an executable file, DLL, or icon file from which icons will
            ///     be extracted.
            ///
            ///
            ///    
            ///         Specifies the zero-based index of the first icon to extract. For
            ///         example, if this value is zero, the function extracts the first
            ///         icon in the specified file.
            ///    
            ///    
            ///         If this value is �1 and and
            ///         are both NULL, the function returns
            ///         the total number of icons in the specified file. If the file is an
            ///         executable file or DLL, the return value is the number of
            ///         RT_GROUP_ICON resources. If the file is an .ico file, the return
            ///         value is 1.
            ///    
            ///    
            ///         Windows 95/98/Me, Windows NT 4.0 and later: If this value is a
            ///         negative number and either or
            ///         is not NULL, the function begins by
            ///         extracting the icon whose resource identifier is equal to the
            ///         absolute value of . For example, use -3
            ///         to extract the icon whose resource identifier is 3.
            ///    
            ///
            ///
            ///     An array of icon handles that receives handles to the large icons
            ///     extracted from the file. If this parameter is NULL, no large icons
            ///     are extracted from the file.
            ///
            ///
            ///     An array of icon handles that receives handles to the small icons
            ///     extracted from the file. If this parameter is NULL, no small icons
            ///     are extracted from the file.
            ///
            ///
            ///     Specifies the number of icons to extract from the file.
            ///
            ///
            ///     If the parameter is -1, the
            ///     parameter is NULL, and the
            ///     parameter is NULL, then the return
            ///     value is the number of icons contained in the specified file.
            ///     Otherwise, the return value is the number of icons successfully
            ///     extracted from the file.
            ///
            [DllImport("Shell32", CharSet = CharSet.Auto)]
            extern static int ExtractIconEx(
                [MarshalAs(UnmanagedType.LPTStr)]
            string lpszFile,
                int nIconIndex,
                IntPtr[] phIconLarge,
                IntPtr[] phIconSmall,
                int nIcons);

            [DllImport("Shell32", CharSet = CharSet.Auto)]
            extern static IntPtr SHGetFileInfo(
                string pszPath,
                int dwFileAttributes,
                out SHFILEINFO psfi,
                int cbFileInfo,
                FileInfoFlags uFlags);

            #endregion

            ///
            /// Two constants extracted from the FileInfoFlags, the only that are
            /// meaningfull for the user of this class.
            ///
            public enum SystemIconSize : int
            {
                Large = 0x000000000,
                Small = 0x000000001
            }

            ///
            /// Get the number of icons in the specified file.
            ///
            /// Full path of the file to look for.
            ///
            static int GetIconsCountInFile(string fileName)
            {
                return ExtractIconEx(fileName, -1, null, null, 0);
            }

            #region ExtractIcon-like functions

            public static void ExtractEx(string fileName, List largeIcons,
                List smallIcons, int firstIconIndex, int iconCount)
            {
                /*
                 * Memory allocations
                 */

                IntPtr[] smallIconsPtrs = null;
                IntPtr[] largeIconsPtrs = null;

                if (smallIcons != null)
                {
                    smallIconsPtrs = new IntPtr[iconCount];
                }
                if (largeIcons != null)
                {
                    largeIconsPtrs = new IntPtr[iconCount];
                }

                /*
                 * Call to native Win32 API
                 */

                int apiResult = ExtractIconEx(fileName, firstIconIndex, largeIconsPtrs, smallIconsPtrs, iconCount);
                if (apiResult != iconCount)
                {
                    throw new UnableToExtractIconsException(fileName, firstIconIndex, iconCount);
                }

                /*
                 * Fill lists
                 */

                if (smallIcons != null)
                {
                    smallIcons.Clear();
                    foreach (IntPtr actualIconPtr in smallIconsPtrs)
                    {
                        smallIcons.Add(Icon.FromHandle(actualIconPtr));
                    }
                }
                if (largeIcons != null)
                {
                    largeIcons.Clear();
                    foreach (IntPtr actualIconPtr in largeIconsPtrs)
                    {
                        largeIcons.Add(Icon.FromHandle(actualIconPtr));
                    }
                }
            }

            public static List ExtractEx(string fileName, SystemIconSize size,
                int firstIconIndex, int iconCount)
            {
                List iconList = new List();

                switch (size)
                {
                    case SystemIconSize.Large:
                        ExtractEx(fileName, iconList, null, firstIconIndex, iconCount);
                        break;

                    case SystemIconSize.Small:
                        ExtractEx(fileName, null, iconList, firstIconIndex, iconCount);
                        break;

                    default:
                        throw new ArgumentOutOfRangeException("size");
                }

                return iconList;
            }

            public static void Extract(string fileName, List largeIcons, List smallIcons)
            {
                int iconCount = GetIconsCountInFile(fileName);
                ExtractEx(fileName, largeIcons, smallIcons, 0, iconCount);
            }

            public static List Extract(string fileName, SystemIconSize size)
            {
                int iconCount = GetIconsCountInFile(fileName);
                return ExtractEx(fileName, size, 0, iconCount);
            }

            public static Icon ExtractOne(string fileName, int index, SystemIconSize size)
            {
                try
                {
                    List iconList = ExtractEx(fileName, size, index, 1);
                    return iconList[0];
                }
                catch (UnableToExtractIconsException)
                {
                    throw new IconNotFoundException(fileName, index);
                }
            }

            public static void ExtractOne(string fileName, int index,
                out Icon largeIcon, out Icon smallIcon)
            {
                List smallIconList = new List();
                List largeIconList = new List();
                try
                {
                    ExtractEx(fileName, largeIconList, smallIconList, index, 1);
                    largeIcon = largeIconList[0];
                    smallIcon = smallIconList[0];
                }
                catch (UnableToExtractIconsException)
                {
                    throw new IconNotFoundException(fileName, index);
                }
            }

            #endregion

            //this will look throw the registry
            //to find if the Extension have an icon.
            public static Icon IconFromExtension(string extension,
                                                    SystemIconSize size)
            {
                // Add the '.' to the extension if needed
                if (extension[0] != '.') extension = '.' + extension;

                //opens the registry for the wanted key.
                RegistryKey Root = Registry.ClassesRoot;
                RegistryKey ExtensionKey = Root.OpenSubKey(extension);
                ExtensionKey.GetValueNames();
                RegistryKey ApplicationKey =
                    Root.OpenSubKey(ExtensionKey.GetValue("").ToString());

                //gets the name of the file that have the icon.
                string IconLocation =
                    ApplicationKey.OpenSubKey("DefaultIcon").GetValue("").ToString();
                string[] IconPath = IconLocation.Split(',');

                if (IconPath[1] == null) IconPath[1] = "0";
                IntPtr[] Large = new IntPtr[1], Small = new IntPtr[1];

                //extracts the icon from the file.
                ExtractIconEx(IconPath[0],
                    Convert.ToInt16(IconPath[1]), Large, Small, 1);
                return size == SystemIconSize.Large ?
                    Icon.FromHandle(Large[0]) : Icon.FromHandle(Small[0]);
            }

            public static Icon IconFromExtensionShell(string extension, SystemIconSize size)
            {
                //add '.' if nessesry
                if (extension[0] != '.') extension = '.' + extension;

                //temp struct for getting file shell info
                SHFILEINFO fileInfo = new SHFILEINFO();

                SHGetFileInfo(
                    extension,
,
                    out fileInfo,
                    Marshal.SizeOf(fileInfo),
                    FileInfoFlags.SHGFI_ICON | FileInfoFlags.SHGFI_USEFILEATTRIBUTES | (FileInfoFlags)size);

                return Icon.FromHandle(fileInfo.hIcon);
            }

            public static Icon IconFromResource(string resourceName)
            {
                Assembly assembly = Assembly.GetCallingAssembly();

                return new Icon(assembly.GetManifestResourceStream(resourceName));
            }

            ///
            /// Parse strings in registry who contains the name of the icon and
            /// the index of the icon an return both parts.
            ///
            /// The full string in the form "path,index" as found in registry.
            /// The "path" part of the string.
            /// The "index" part of the string.
            public static void ExtractInformationsFromRegistryString(
                string regString, out string fileName, out int index)
            {
                if (regString == null)
                {
                    throw new ArgumentNullException("regString");
                }
                if (regString.Length == 0)
                {
                    throw new ArgumentException("The string should not be empty.", "regString");
                }

                index = 0;
                string[] strArr = regString.Replace(""", "").Split(',');
                fileName = strArr[0].Trim();
                if (strArr.Length > 1)
                {
                    int.TryParse(strArr[1].Trim(), out index);
                }
            }

            public static Icon ExtractFromRegistryString(string regString, SystemIconSize size)
            {
                string fileName;
                int index;
                ExtractInformationsFromRegistryString(regString, out fileName, out index);
                return ExtractOne(fileName, index, size);
            }
        }
    }
}       

代码如下:

///
        /// 应用程序的主入口点。
        ///
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            PictureBox pict = new PictureBox();
            pict.Image = BlackFox.Win32.Icons.IconFromExtension(".zip", BlackFox.Win32.Icons.SystemIconSize.Large).ToBitmap();
            pict.Dock = DockStyle.Fill;
            pict.SizeMode = PictureBoxSizeMode.CenterImage;

            Form form = new Form();
            form.Controls.Add(pict);
            Application.Run(form);
        }

    
 
 

您可能感兴趣的文章:

  • windows/windows 7/windows 8 下打开查看、修改及保存超大(GB级)文本文件及其它类型文件的工具-PilotEdit
  • 因为开启了文件类型检测,Vim在打开或新建一个文件时会自动判断文件的扩展名以确定文件类型,在$VIMRUNTIME/filetype.vim中搜索"Makefi
  • linux修改所有文件类型为文本类型
  • 请问:在proc程序中,若里面有模板的类型,能不能通过预编译啊,(编译时老是无法识别类型,我的头文件都已包含了)
  • 如何用高效快捷的方式获得 文件大小 文件类型 文件更新日前?
  • 如何获取 文件类型?文件更新日期?多谢高手帮忙!
  • 如何用DOS批量move多文件夹下的同类型文件
  • jquery判断上传文件类型与限制文件大小
  • C如何获取某文件中某一类型文件,且对其排列
  • 上传文件时在弹出框如何指定某类型文件如(*.jpg)
  • 怎么知道操作系统的文件系统类型
  • PHP取二进制文件头判断文件类型
  • 如何运行-rwxr-xr-x类型的文件?
  • linux操作系统下的data类型文件问题
  • 有谁知道用什么命令可以在dos下建立新文件,并且定义文件的类型吗?还有怎么在dos下修改文件的属性呢?
  • 请问在WINDOWS下用什么软件解开JAR类型文件?
  • 怎么调用某种类型文件,让其被默认的应用程序打开----着急!!!
  • 请教:solaris下如何打印文件,需要支持选择纸张类型和选择黑白彩色!
  • linux配置新建某类型文件具有可执行权限
  • 如何新建一个特定类型的文件?
  • 文件系统类型更改工具 fstransform
  • c#如何生成Excel(.xls和.xlsx)文件
  • 将ocx文件转换成C#程序引用的DLL文件的办法
  • C#删除文件夹和文件到回收站示例
  • C#逐行读取txt文件的方法
  • c# 递归访问文件夹(删掉歌词文件)
  • C# WinForm编程获取文件物理路径的方法
  • C#文件管理类Directory实例分析
  • c#文件夹 递归访问的实现代码
  • c# 删除空文件夹的代码
  • C#清空添加的txt文件的实例代码
  •  
    本站(WWW.)旨在分享和传播互联网科技相关的资讯和技术,将尽最大努力为读者提供更好的信息聚合和浏览方式。
    本站(WWW.)站内文章除注明原创外,均为转载、整理或搜集自网络。欢迎任何形式的转载,转载请注明出处。












  • 相关文章推荐
  • linux文件上添加小图标
  • 为什么在FC4下双击文件夹图标,是在另外一个窗口中显示该文件夹的文件?
  • 为什么在FC4下双击文件夹图标,是在另外一个窗口中显示该文件夹的文件?
  • java根据扩展名获取系统图标和文件图标示例
  • 如何给jar文件加一个图标呢?谢谢!
  • php开源软件 iis7站长之家
  • !!!为什么我的文件图标不一样?(在线等待,既可结帖)
  • C++ I/O 成员 eof():如果处于文件结尾处则返回true
  • Shell脚本如何递归现实一个文件夹中的文件(文件夹中含有文件夹)
  • WinDows8最新版文件夹加密
  • 求命令:什么命令可以把文件夹下所有的文件按修改时间先后排出来,包括子文件夹里的文件。
  • sharepoint 2010 使用STSNavigate函数实现文件下载举例
  • [提问]Linux下如何把多个.a文件编译一个.so文件,或者把多个.so文件编译成一个.so文件
  • python异常信息堆栈输出到日志文件
  • 请问:proc中的头文件中能包含头文件吗?(感觉如果头文件中包含头文件的话,在链接时就会有错误啊)
  • Centos6下安装Shell下文件上传下载rz,sz命令
  • 我要实现当进程打开文件时,根据文件名判断是否符合要求,符合后处理文件,再把文件返回给进程,怎么实现啊
  • 在MyEclipse中设开启xml文件自动提示和自动完成功能
  • vi 中编辑两个文件,怎样从其中一个文件拷一段内容到另一个文件中。(同时打开两个文件)
  • 修改配置真正解决php文件上传大小限制问题(nginx+php)
  • 怎么统计一个文件夹下有多少个文件(不包括文件夹)
  • 修改配置真正解决php文件上传大小限制问题(apache+php)
  • 请教高手一个简单问题:给定一个文件名,如何去查找该文件正在被几个程序使用,并怎么样才可以切断这个文件与正在打开该文件的程序之间的
  • MyEclipse如何查看和设置文件编码格式相关操作
  • linux 下的 .a 文件 .o 文件 是什么文件?各有什么作用?
  • 使用libpcap读取tcpdump抓取的文件并解析c代码实例
  • 如何用socket一次传输多个文件,如何确定文件一个文件结束
  • 设置sharepoint 2010文档库中的 pdf文件在浏览器中访问的打开方式
  • 如何删除某个目录下除了指定文件夹之外的所有文件和文件夹


  • 站内导航:


    特别声明:169IT网站部分信息来自互联网,如果侵犯您的权利,请及时告知,本站将立即删除!

    ©2012-2021,,E-mail:www_#163.com(请将#改为@)

    浙ICP备11055608号-3