使用非托管代码使用扩展名获取文件图标时,在x86系统上获取exception

我正在开发磁盘目录应用程序,它要求我使用从数据库中检索的文件扩展名来获取文件图标。 使用他们的扩展程序获取文件图标的代码在我的Windows 7 x64机器上使用任何CPU调试配置都可以正常工作,但是当我在调试配置中切换到x86时,我得到以下错误。

致命执行引擎错误

当我试图在任何CPU配置的Windows XP x86中运行该应用程序时,我得到以下错误。

尝试读取或写入受保护的内存。 这通常表明其他内存已损坏

当我删除下面的代码应用程序完美无缺。 我想使用下面的代码从扩展名获取文件图标。 是否有任何解决方法来使代码在x86系统上工作? 我发现这个代码来自如何在C#中获取常见的文件类型图标? 。

///  /// Contains information about a file object. ///  struct SHFILEINFO { ///  /// Handle to the icon that represents the file. You are responsible for /// destroying this handle with DestroyIcon when you no longer need it. ///  public IntPtr HIcon; }; [Flags] enum FileInfoFlags { ///  /// Retrieve the handle to the icon that represents the file and the index /// of the icon within the system image list. The handle is copied to the /// hIcon member of the structure specified by psfi, and the index is copied /// to the iIcon member. ///  ShgfiIcon = 0x000000100, ///  /// Indicates that the function should not attempt to access the file /// specified by pszPath. Rather, it should act as if the file specified by /// pszPath exists with the file attributes passed in dwFileAttributes. ///  ShgfiUsefileattributes = 0x000000010 } [DllImport("Shell32", CharSet = CharSet.Auto)] extern static IntPtr SHGetFileInfo( string pszPath, int dwFileAttributes, out SHFILEINFO psfi, int cbFileInfo, FileInfoFlags uFlags); ///  /// Two constants extracted from the FileInfoFlags, the only that are /// meaningfull for the user of this class. ///  public enum IconSize { Large = 0x000000000, Small = 0x000000001 } ///  /// Get the icon associated with file Extension. ///  /// Search icon for this file extension /// Icon size ///  public static Icon GetIcon(string fileExt ,IconSize size) { var fileInfo = new SHFILEINFO(); SHGetFileInfo(fileExt, 0, out fileInfo, Marshal.SizeOf(fileInfo), FileInfoFlags.ShgfiIcon | FileInfoFlags.ShgfiUsefileattributes | (FileInfoFlags)size); return Icon.FromHandle(fileInfo.HIcon); } 

您对SHFILEINFO定义不完整。 原来看起来像

 typedef struct _SHFILEINFO { HICON hIcon; int iIcon; DWORD dwAttributes; TCHAR szDisplayName[MAX_PATH]; TCHAR szTypeName[80]; } SHFILEINFO; 

在C#中应该看起来像

 [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] struct SHFILEINFO { public IntPtr hIcon; public int iIcon; public uint dwAttributes; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string szDisplayName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)] public string szTypeName; }