首页 / C# / c# – 3310次成功后方法失败
c# – 3310次成功后方法失败
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 3310次成功后方法失败,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2182字,纯文字阅读大概需要4分钟。
内容图文
![c# – 3310次成功后方法失败](/upload/InfoBanner/zyjiaocheng/820/9b8d7df2a06e4a4c8f5fd72f535ff921.jpg)
我继承了以下扩展方法,该方法基于文件路径创建ImageSource对象
public static class ImageSourceExtensions
{
[StructLayout(LayoutKind.Sequential)]
public 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;
};
public const uint SHGFI_ICON = 0x100;
public const uint SHGFI_LARGEICON = 0x0;
[DllImport("shell32.dll")]
public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbSizeFileInfo, uint uFlags);
public static ImageSource GetIconFromFolder(this string filePath)
{
SHFILEINFO shinfo = new SHFILEINFO();
SHGetFileInfo(filePath, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo),
SHGFI_ICON | SHGFI_LARGEICON);
using (Icon i = Icon.FromHandle(shinfo.hIcon))
{
//Convert icon to a Bitmap source
ImageSource img = Imaging.CreateBitmapSourceFromHIcon(
i.Handle,
new Int32Rect(0, 0, i.Width, i.Height),
BitmapSizeOptions.FromEmptyOptions());
return img;
}
}
}
此扩展方法适用于文件夹和文件3310次.在第3311个方法调用上,抛出以下异常:
‘Win32 handle that was passed to Icon is not valid or is the wrong
type’
使用shinfo.hIcon属性时抛出此错误.
该错误最初是在我的主应用程序中抛出的,并且每次都在不同的文件上.我已经将这个类提取到一个新项目中,并且可以通过在单击按钮上执行此操作来获得相同的错误(在相同的次数之后):
String path = @"C:\Generic Folder\Generic Document.pdf";
for (int i = 0; i <4000; i++)
{
ImageSource img = path.GetIconFromFolder();
}
有人知道这个的明显原因吗?
解决方法:
你的HANDLEs已经不多了. Windows具有有限数量的句柄,当您获得一个句柄(在这种情况下是图标的句柄)时,您应该在不再使用它之后释放它.如果不这样做,Windows将耗尽免费句柄.
If SHGetFileInfo returns an icon handle in the hIcon member of the SHFILEINFO structure pointed to by psfi, you are responsible for freeing it with DestroyIcon when you no longer need it.
因此,您需要PInvoke DestroyIcon并在函数结束时将shinfo.hIcon传递给它.
使用FromHandle创建的Icon的处理不会破坏原始句柄:
When using this method, you must dispose of the original icon by using the DestroyIcon method in the Win32 API to ensure that the resources are released.
内容总结
以上是互联网集市为您收集整理的c# – 3310次成功后方法失败全部内容,希望文章能够帮你解决c# – 3310次成功后方法失败所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。