Windows Forms: Extract the Icon Associated with a File in C#

This post shows you how to Extract the Icon Associated with a File in C# Windows Forms Application.

Drag the ListView and ImageList controls from the visual toolbox to your winform.

c# get file icon

You should set the LargeImageList property of ListView control to the ImageList.

Add code to handle form load event as shown below.

private void Form1_Load(object sender, EventArgs e)
{
    using (ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher("select ProcessId, Name, ExecutablePath from Win32_Process"))
    {
        using (var results = managementObjectSearcher.Get())
        {
            var processes = results.Cast<ManagementObject>().Select(p => new
            {
                ProcessId = (UInt32)p["ProcessId"],
                Name = (string)p["Name"],
                ExecutablePath = (string)p["ExecutablePath"]
            });
            foreach (var pro in processes)
            {
                if (System.IO.File.Exists(pro.ExecutablePath))
                {
                    var icon = Icon.ExtractAssociatedIcon(pro.ExecutablePath);
                    var key = pro.ProcessId.ToString();
                    this.imageList1.Images.Add(key, icon.ToBitmap());
                    this.listView1.Items.Add(pro.Name, key);
                }
            }
        }
    }
}

You need to add a reference to the System.Management.dll, and don't forget to import the namespace below.

using System.Management;

Press F5 to run your project, we will get all process, then extract the icon associated with the process.