Skip to content

Commit

Permalink
Handle problems getting the icon for a file
Browse files Browse the repository at this point in the history
Fixes #224
  • Loading branch information
canton7 committed Jan 30, 2016
1 parent a7e6f7f commit c9ee344
Showing 1 changed file with 23 additions and 4 deletions.
27 changes: 23 additions & 4 deletions src/SyncTrayzor/Utils/ShellTools.cs
Original file line number Diff line number Diff line change
@@ -1,27 +1,46 @@
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using NLog;

namespace SyncTrayzor.Utils
{
// See http://codesdirectory.blogspot.co.uk/2013/01/displaying-system-icon-in-c-wpf.html
public static class ShellTools
{
private static readonly Logger logger = LogManager.GetCurrentClassLogger();

public static Icon GetIcon(string path, bool isFile)
{
var flags = (uint)(SHGFI_ICON | SHGFI_USEFILEATTRIBUTES | SHGFI_LARGEICON);
var attribute = isFile ? (uint)FILE_ATTRIBUTE_FILE : (uint)FILE_ATTRIBUTE_DIRECTORY;
var shfi = new SHFileInfo();
var res = NativeMethods.SHGetFileInfo(path, attribute, out shfi, (uint)Marshal.SizeOf(shfi), flags);
IntPtr res;
try
{
res = NativeMethods.SHGetFileInfo(path, attribute, out shfi, (uint)Marshal.SizeOf(shfi), flags);
}
catch (Exception e)
{
logger.Error(e, $"Unable to call SHGetFileInfo: {e.Message}");
return null;
}

if (res == IntPtr.Zero)
throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());
{
logger.Error(Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error()), "SHGetFileInfo returned zero");
return null;
}

try
{
Icon.FromHandle(shfi.hIcon);
return (Icon)Icon.FromHandle(shfi.hIcon).Clone();
}
catch(Exception e)
{
logger.Error(e, $"Failed to call Icon.FromHandle: {e.Message}");
return null;
}
finally
{
NativeMethods.DestroyIcon(shfi.hIcon);
Expand Down Expand Up @@ -50,7 +69,7 @@ private struct SHFileInfo
private const uint FILE_ATTRIBUTE_DIRECTORY = 0x00000010;
private const uint FILE_ATTRIBUTE_FILE = 0x00000100;

private class NativeMethods
private static class NativeMethods
{
[DllImport("shell32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, out SHFileInfo psfi, uint cbFileInfo, uint uFlags);
Expand Down

0 comments on commit c9ee344

Please sign in to comment.