根據文件名或文件擴展名獲取文件的默認圖標


新建一個vs2010 窗體項目,新建按鈕button和圖片picturebox
下面是程序

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace findIconWithPathFile
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

string xx = null;
private void button1_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(xx) == true)
{
using (OpenFileDialog dlg = new OpenFileDialog())
{
dlg.CheckFileExists = true;
dlg.CheckPathExists = true;
dlg.Filter = "所有文件(*.*)|*.*";
if (dlg.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
{
xx = dlg.FileName;
}
}
//Icon icon= getIcon(xx ,true);
Icon icon = getIcon1(xx);
pictureBox1.Image = icon.ToBitmap();
}
}

[DllImport("shell32.dll")]
public extern static uint ExtractIconEx(string lpszFile, int nIconIndex, int[] phiconLarge, int[] phiconSmall, uint nIcons);

public Icon getIcon(string pathxx, bool large)
{
int[] phiconLarge = new int[1];
int[] phiconSmall = new int[1];
ExtractIconEx(pathxx, 0, phiconLarge, phiconSmall, 1);
IntPtr handle = new IntPtr(large ? phiconLarge[0] : phiconSmall[0]);
Icon icon = Icon.FromHandle(handle);

return icon;
}

public Icon getIcon1(string pathxx)
{

 Icon image= Icon.ExtractAssociatedIcon(Filepath).ToBitmap();//轉換一下

Icon icon = Icon.ExtractAssociatedIcon(pathxx);

return icon;
}
}
}

 
 
 
根據不同的文件擴展名顯示不同的圖標,在C#中可以使用 Icon icon = System.Drawing.Icon.ExtractAssociatedIcon(fileFullName) 來得到指定文件圖標。
       /// <summary>
        /// 依據文件名讀取圖標,若指定文件不存在,則返回空值。  
        /// </summary>
        /// <param name="fileName">文件路徑</param>
        /// <param name="isLarge">是否返回大圖標</param>
        /// <returns></returns>
        public static Icon GetIconByFileName(string fileName, bool isLarge = true)
        {
            int[] phiconLarge = new int[1];
            int[] phiconSmall = new int[1];
            //文件名 圖標索引 
            try
            {
                Win32.ExtractIconEx(fileName, 0, phiconLarge, phiconSmall, 1);
                IntPtr IconHnd = new IntPtr(isLarge ? phiconLarge[0] : phiconSmall[0]);
                return Icon.FromHandle(IconHnd);
            }
            catch {
                return null;
            }
        } 
 
 /// <summary>  
        /// 根據文件擴展名(如:.*),返回與之關聯的圖標。
        /// 若不以"."開頭則返回文件夾的圖標。  
        /// </summary>  
        /// <param name="fileType">文件擴展名</param>  
        /// <param name="isLarge">是否返回大圖標</param>  
        /// <returns></returns>  
        public static Icon GetIconByFileType(string fileType, bool isLarge)
        {
            if (fileType == null || fileType.Equals(string.Empty)) return null;

            RegistryKey regVersion = null;
            string regFileType = null;
            string regIconString = null;
            string systemDirectory = Environment.SystemDirectory + "\\";

            if (fileType[0] == '.')
            {
                //讀系統注冊表中文件類型信息  
                regVersion = Registry.ClassesRoot.OpenSubKey(fileType, true);
                if (regVersion != null)
                {
                    regFileType = regVersion.GetValue("") as string;
                    regVersion.Close();
                    regVersion = Registry.ClassesRoot.OpenSubKey(regFileType + @"\DefaultIcon", true);
                    if (regVersion != null)
                    {
                        regIconString = regVersion.GetValue("") as string;
                        regVersion.Close();
                    }
                }
                if (regIconString == null)
                {
                    //沒有讀取到文件類型注冊信息,指定為未知文件類型的圖標  
                    regIconString = systemDirectory + "shell32.dll,0";
                }
            }
            else
            {
                //直接指定為文件夾圖標  
                regIconString = systemDirectory + "shell32.dll,3";
            }
            string[] fileIcon = regIconString.Split(new char[] { ',' });
            if (fileIcon.Length != 2)
            {
                //系統注冊表中注冊的標圖不能直接提取,則返回可執行文件的通用圖標  
                fileIcon = new string[] { systemDirectory + "shell32.dll", "2" };
            }
            Icon resultIcon = null;
            try
            {
                //調用API方法讀取圖標  
                int[] phiconLarge = new int[1];
                int[] phiconSmall = new int[1];
                uint count = Win32.ExtractIconEx(fileIcon[0], Int32.Parse(fileIcon[1]), phiconLarge, phiconSmall, 1);
                IntPtr IconHnd = new IntPtr(isLarge ? phiconLarge[0] : phiconSmall[0]);
                resultIcon = Icon.FromHandle(IconHnd);
            }
            catch { }
            return resultIcon;
        }
    } 
 
 
雖然在C#中可以使用 Icon icon = System.Drawing. Icon .ExtractAssociatedIcon(fileFullName) 來得到指定文件圖標。但是Icon.ExtractAssociatedIcon 只能獲取大圖標,要獲取小圖標還是要使用 API。

 

using System;
using System.Runtime.InteropServices;
using System.Drawing;

 

namespace MyNamespace
{
    public class FileIcon
    {
        /// <summary>
        ///  獲取文件的默認圖標
        /// </summary>
        /// <param name="fileName">文件名。
        ///     可以只是文件名,甚至只是文件的擴展名(.*);
        ///     如果想獲得.ICO文件所表示的圖標,則必須是文件的完整路徑。
        /// </param>
        /// <param name="largeIcon">是否大圖標</param>
        /// <returns>文件的默認圖標</returns>
        public static Icon GetFileIcon(string fileName, bool largeIcon)
        {
            SHFILEINFO info = new SHFILEINFO(true);
            int cbFileInfo = Marshal.SizeOf(info);
            SHGFI flags;
            if (largeIcon)
                flags = SHGFI.Icon | SHGFI.LargeIcon | SHGFI.UseFileAttributes;
            else
                flags = SHGFI.Icon | SHGFI.SmallIcon | SHGFI.UseFileAttributes;

            SHGetFileInfo(fileName, 256, out info, (uint)cbFileInfo, flags);
            return Icon.FromHandle(info.hIcon);
        }

        [DllImport("Shell32.dll")]
        private static extern int SHGetFileInfo
          (
          string pszPath,
          uint dwFileAttributes,
          out   SHFILEINFO psfi,
          uint cbfileInfo,
          SHGFI uFlags
          );
 
        [StructLayout(LayoutKind.Sequential)]
        private struct SHFILEINFO
        {
            public SHFILEINFO(bool b)
            {
                hIcon = IntPtr.Zero; iIcon = 0; dwAttributes = 0; szDisplayName = ""; szTypeName = "";
            }
            public IntPtr hIcon;
            public int iIcon;
            public uint dwAttributes;
            [MarshalAs(UnmanagedType.LPStr, SizeConst = 260)]
            public string szDisplayName;
            [MarshalAs(UnmanagedType.LPStr, SizeConst = 80)]
            public string szTypeName;
        };
 
        private enum SHGFI
        {
            SmallIcon = 0x00000001,
            LargeIcon = 0x00000000,
            Icon = 0x00000100,
            DisplayName = 0x00000200,
            Typename = 0x00000400,
            SysIconIndex = 0x00004000,
            UseFileAttributes = 0x00000010
        }
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM