How to Extract the Icon Associated with a File in C#
By FoxLearn Published on Jul 16, 2024 6.96K
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.
You should set the LargeImageList property of ListView control to the ImageList.
Add code to handle form load event as shown below.
// icon extractor winform c# 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.
Categories
Popular Posts
11 Things You Didn't Know About Cloudflare
Dec 19, 2024
AdminKit Bootstrap 5 HTML5 UI Kits Template
Nov 17, 2024
RuangAdmin Template
Nov 13, 2024
Admin BSB Free Bootstrap Admin Dashboard
Nov 14, 2024