LinQ has always fascinated me ever since it was first released and I have been learning it ever since. The following snippet could act as a tutorial, especially to the beginners thriving to learn LinQ. Before writing this, I did a bit of browsing on how to get the associated icon for the file extension. I found many likely hits using primitive techniques but none using LinQ. So I decided to write one myself. Even though the code isn’t optimized, it does what it is meant to do and more, it is quite simple to read and understand. Here goes:
var x = from A in
from B in
from C in
from D in
(from E in Registry.ClassesRoot.GetSubKeyNames()
where
E.StartsWith(“.”)
select
new
{ Extension = E,
Key =
Convert.ToString(Registry.ClassesRoot.OpenSubKey(E).GetValue(“”))
})
where D != null
select new {D.Extension, Ico = Registry.ClassesRoot.OpenSubKey(D.Key)}
where C.Ico != null
select new {C.Extension, Val = C.Ico.OpenSubKey(“DefaultIcon”)}
where B.Val != null
select new {B.Extension, FilePath = B.Val.GetValue(“”) as String}
where A != null && A.FilePath != null && A.FilePath.Split(‘,’).Length > 1
select
new
{
A.FilePath,
A.Extension,
Icon =
My.Utilities.IconExtractor.GetIcon(A.FilePath.Split(‘,’).ToArray()[0],
Convert.ToInt32(A.FilePath.Split(‘,’).ToArray()[1]))
};
And another utility class to extract icon from file.
namespace My.Utilities
{
using System;
using System.Runtime.InteropServices;
using System.Drawing;
public class IconExtractor
{
[DllImport("Kernel32.dll")]
static extern int GetModuleHandle(string lpModuleName);
[DllImport("Shell32.dll")]
static extern IntPtr ExtractIcon(int Hinst, string FileName, int IconIndex);
[DllImport("User32.dll")]
static extern int DestroyIcon(IntPtr hIcon);
public static Icon GetIcon(string fileName,int index)
{
IntPtr HIcon=IntPtr.Zero;
try
{
HIcon = ExtractIcon(GetModuleHandle(String.Empty), fileName, index);
if (HIcon == IntPtr.Zero) return null;
return Icon.FromHandle(HIcon).Clone() as Icon;
}
finally
{
DestroyIcon(HIcon);
}
}
}
}
Filed under: Uncategorized | Leave a Comment »