File.ExtractIconFromExecutable Method

Extracts the icon from executable (EXE).
public static Icon ExtractIconFromExecutable( 
string path 
)
This language is not supported or no code example is available.

Parameters

path
string

The path to an EXE file.

Return Value

Icon

A new Icon object that was loaded from an ICO file or extracted from an EXE file. If the icon could not be retrieved, null reference (Nothing in Visual Basic) is returned.

public static Icon ExtractIconFromExecutable(string path)
 {
     IntPtr module = IntPtr.Zero;
     try
     {
         module = Import.LoadLibraryEx(path, IntPtr.Zero, 2);
         if (module == IntPtr.Zero) throw new Win32Exception();
         Icon result = null;
         Import.EnumResourceNames(module, (IntPtr)14, (mod, type, name, lParam) =>
         {
             byte[] groupIcon = Import.GetDataFromResource(module, (IntPtr)14, name);
             int count = BitConverter.ToUInt16(groupIcon, 4);
             int size = 6 + count * 16 + Enumerable.Range(0, count).Select(i => BitConverter.ToInt32(groupIcon, 6 + i * 14 + 8)).Sum();
             using (MemoryStream memoryStream = new MemoryStream(size))
             {
                 using (BinaryWriter writer = new BinaryWriter(memoryStream))
                 {
                     writer.Write(groupIcon, 0, 6);
                     for (int i = 0, offset = 6 + count * 16; i < count; ++i)
                     {
                         byte[] icon = Import.GetDataFromResource(module,
                             (IntPtr)3,
                             (IntPtr)BitConverter.ToUInt16(groupIcon, 6 + i * 14 + 12));
                         writer.Seek(6 + i * 16, SeekOrigin.Begin);
                         writer.Write(groupIcon, 6 + i * 14, 8);
                         writer.Write(icon.Length);
                         writer.Write(offset);
                         writer.Seek(offset, SeekOrigin.Begin);
                         writer.Write(icon, 0, icon.Length);
                         offset += icon.Length;
                     }
                 }
                 using (MemoryStream iconStream = new MemoryStream(memoryStream.ToArray()))
                     result = new Icon(iconStream);
             }
             return false;
         }, IntPtr.Zero);
         return result;
     }
     catch
     {
         return null;
     }
     finally
     {
         if (module != IntPtr.Zero)
             Import.FreeLibrary(module);
     }
 }
					
This language is not supported or no code example is available.

.NET Framework

Supported in: 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8

.NET Core

Supported in: 5.0+, 6.0+

In this article

Definition