How to Extract the Icon Associated with a File in C#

By FoxLearn 7/16/2024 9:18:37 AM   6.02K
You can extract the icon associated with a file in a C# Windows Forms application using the Icon.ExtractAssociatedIcon method from the System.Drawing namespace.

How to extract the icon associated with a file in C#

Drag and drop 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;

In this example, the code retrieves the associated icon using Icon.ExtractAssociatedIcon. Then, it converts the icon to a bitmap format and add it into a ImageList.

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