How to get the associated icon from a network share file

后端 未结 5 1444
深忆病人
深忆病人 2020-12-07 00:21

I am using Icon.ExtractAssociatedIcon to get the icon of a file , that a user selects, in an openfiledialog.

THe problem is if the user selects an icon from a netw

5条回答
  •  星月不相逢
    2020-12-07 00:51

    For completeness' sake, here's an ExtractAssociatedIcon routine that works:

    /// 
    /// Returns an icon representation of an image contained in the specified file.
    /// This function is identical to System.Drawing.Icon.ExtractAssociatedIcon, xcept this version works.
    /// 
    /// The path to the file that contains an image.
    /// The System.Drawing.Icon representation of the image contained in the specified file.
    /// filePath does not indicate a valid file.
    public static Icon  ExtractAssociatedIcon(String filePath)
    {
        int index = 0;
    
        Uri uri;
        if (filePath == null)
        {
            throw new ArgumentException(String.Format("'{0}' is not valid for '{1}'", "null", "filePath"), "filePath");
        }
        try
        {
            uri = new Uri(filePath);
        }
        catch (UriFormatException)
        {
            filePath = Path.GetFullPath(filePath);
            uri = new Uri(filePath);
        }
        //if (uri.IsUnc)
        //{
        //  throw new ArgumentException(String.Format("'{0}' is not valid for '{1}'", filePath, "filePath"), "filePath");
        //}
        if (uri.IsFile)
        {
            if (!File.Exists(filePath))
            {
                //IntSecurity.DemandReadFileIO(filePath);
                throw new FileNotFoundException(filePath);
            }
    
            StringBuilder iconPath = new StringBuilder(260);
            iconPath.Append(filePath);
    
            IntPtr handle = SafeNativeMethods.ExtractAssociatedIcon(new HandleRef(null, IntPtr.Zero), iconPath, ref index);
            if (handle != IntPtr.Zero)
            {
                //IntSecurity.ObjectFromWin32Handle.Demand();
                return Icon.FromHandle(handle);
            }
        }
        return null;
    }
    
    
    /// 
    /// This class suppresses stack walks for unmanaged code permission. 
    /// (System.Security.SuppressUnmanagedCodeSecurityAttribute is applied to this class.) 
    /// This class is for methods that are safe for anyone to call. 
    /// Callers of these methods are not required to perform a full security review to make sure that the 
    /// usage is secure because the methods are harmless for any caller.
    /// 
    [SuppressUnmanagedCodeSecurity]
    internal static class SafeNativeMethods
    {
        [DllImport("shell32.dll", EntryPoint = "ExtractAssociatedIcon", CharSet = CharSet.Auto)]
        internal static extern IntPtr ExtractAssociatedIcon(HandleRef hInst, StringBuilder iconPath, ref int index);
    }
    

    Note: Any code is released into the public domain. No attribution required.

提交回复
热议问题