I have a great technique to get the associated extension/image in the current system (because extensions can have different images from a system to another). And here is the function:
public static Icon getIconFromFile(string ext, bool large = true)
{
string fileName = (new Random()).Next(100, 1000).ToString() + ext;
System.IO.File.Create(fileName);
System.Drawing.Icon icon;
SHFILEINFO shinfo = new SHFILEINFO();
if (large)
{
IntPtr hImgLarge = Win32.SHGetFileInfo(fileName, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), Win32.SHGFI_ICON | Win32.SHGFI_LARGEICON);
icon = System.Drawing.Icon.FromHandle(shinfo.hIcon);
}
else
{
IntPtr hImgSmall = Win32.SHGetFileInfo(fileName, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), Win32.SHGFI_ICON | Win32.SHGFI_SMALLICON);
icon = System.Drawing.Icon.FromHandle(shinfo.hIcon);
}
try
{
System.IO.File.Delete(fileName);
}
catch(Exception e)
{
System.Console.WriteLine(e.StackTrace);
}
return icon;
}
The problem is that the function doesn’t close the access to the file, so i can’t remove it. How can i do ? Thanks
File.Createreturns a stream that references the file you’ve created. To ensure that the stream is closed properly, you should wrap it in ausingblock:It doesn’t matter if you use the returned stream or not, you need to ensure it’s disposed so that the file can be deleted. Note also that I’ve moved the declaration of
iconto outside theusingblock so that you can return it at the end of the method.I should also point out that:
Is a bit of a “bad idea” when you could just as easily call “System.IO.Path.GetTempFileName();” and leave creating the file and uniquely naming it to the Operating System, rather than attempting to do that yourself. THat has the added bonus of the file being created in the users
tempdirectory, which is the best place for it given that it’s a temporary file. You’d also then not encounter the issue of the file being held open (there are various other methods likeSystem.IO.Path.GetExtensionyou could use to rename the file so it has the appropriate extension.