【转】 C# ListView实例:文件图标显示

说明:本例将目录中的文件显示在窗体的ListView控件中,并定义了多种视图浏览。通过调用Win32库函数实现图标数据的提取。

主程序:

大图标:

列表:

详细信息:

Form1.cs:

public partial class Form1 : Form
{
FileInfoList fileList; public Form1()
{
InitializeComponent();
} private void 加载文件ToolStripMenuItem_Click(object sender, EventArgs e)
{
FolderBrowserDialog dlg = new FolderBrowserDialog();
if (dlg.ShowDialog() == DialogResult.OK)
{
string[] filespath = Directory.GetFiles(dlg.SelectedPath);
fileList = new FileInfoList(filespath);
InitListView();
}
} private void InitListView()
{
listView1.Items.Clear();
this.listView1.BeginUpdate();
foreach (FileInfoWithIcon file in fileList.list)
{
ListViewItem item = new ListViewItem();
item.Text = file.fileInfo.Name.Split('.')[0];
item.ImageIndex = file.iconIndex;
item.SubItems.Add(file.fileInfo.LastWriteTime.ToString());
item.SubItems.Add(file.fileInfo.Extension.Replace(".",""));
item.SubItems.Add(string.Format(("{0:N0}"), file.fileInfo.Length));
listView1.Items.Add(item);
}
listView1.LargeImageList = fileList.imageListLargeIcon;
listView1.SmallImageList = fileList.imageListSmallIcon;
listView1.Show();
this.listView1.EndUpdate();
} private void 大图标ToolStripMenuItem_Click(object sender, EventArgs e)
{
listView1.View = View.LargeIcon;
} private void 小图标ToolStripMenuItem_Click(object sender, EventArgs e)
{
listView1.View = View.SmallIcon;
} private void 平铺ToolStripMenuItem_Click(object sender, EventArgs e)
{
listView1.View = View.Tile;
} private void 列表ToolStripMenuItem_Click(object sender, EventArgs e)
{
listView1.View = View.List;
} private void 详细信息ToolStripMenuItem_Click(object sender, EventArgs e)
{
listView1.View = View.Details;
}
}

FileInfoList.cs:

说明:主要用于后台数据的存储
class FileInfoList
{
public List<FileInfoWithIcon> list;
public ImageList imageListLargeIcon;
public ImageList imageListSmallIcon; /// <summary>
/// 根据文件路径获取生成文件信息,并提取文件的图标
/// </summary>
/// <param name="filespath"></param>
public FileInfoList(string[] filespath)
{
list = new List<FileInfoWithIcon>();
imageListLargeIcon = new ImageList();
imageListLargeIcon.ImageSize = new Size(32, 32);
imageListSmallIcon = new ImageList();
imageListSmallIcon.ImageSize = new Size(16, 16);
foreach (string path in filespath)
{
FileInfoWithIcon file = new FileInfoWithIcon(path);
imageListLargeIcon.Images.Add(file.largeIcon);
imageListSmallIcon.Images.Add(file.smallIcon);
file.iconIndex = imageListLargeIcon.Images.Count - 1;
list.Add(file);
}
}
}
class FileInfoWithIcon
{
public FileInfo fileInfo;
public Icon largeIcon;
public Icon smallIcon;
public int iconIndex;
public FileInfoWithIcon(string path)
{
fileInfo = new FileInfo(path);
largeIcon = GetSystemIcon.GetIconByFileName(path, true);
if (largeIcon == null)
largeIcon = GetSystemIcon.GetIconByFileType(Path.GetExtension(path), true); smallIcon = GetSystemIcon.GetIconByFileName(path, false);
if (smallIcon == null)
smallIcon = GetSystemIcon.GetIconByFileType(Path.GetExtension(path), false);
}
}

GetSystemIcon:

说明:定义两种图标获取方式,从文件提取和从文件关联的系统资源中提取。
public static class GetSystemIcon
{
/// <summary>
/// 依据文件名读取图标,若指定文件不存在,则返回空值。
/// </summary>
/// <param name="fileName">文件路径</param>
/// <param name="isLarge">是否返回大图标</param>
/// <returns></returns>
public static Icon GetIconByFileName(string fileName, bool isLarge = true)
{
int[] phiconLarge = new int[1];
int[] phiconSmall = new int[1];
//文件名 图标索引
Win32.ExtractIconEx(fileName, 0, phiconLarge, phiconSmall, 1);
IntPtr IconHnd = new IntPtr(isLarge ? phiconLarge[0] : phiconSmall[0]); if (IconHnd.ToString() == "0")
return null;
return Icon.FromHandle(IconHnd);
} /// <summary>
/// 根据文件扩展名(如:.*),返回与之关联的图标。
/// 若不以"."开头则返回文件夹的图标。
/// </summary>
/// <param name="fileType">文件扩展名</param>
/// <param name="isLarge">是否返回大图标</param>
/// <returns></returns>
public static Icon GetIconByFileType(string fileType, bool isLarge)
{
if (fileType == null || fileType.Equals(string.Empty)) return null; RegistryKey regVersion = null;
string regFileType = null;
string regIconString = null;
string systemDirectory = Environment.SystemDirectory + "\\"; if (fileType[0] == '.')
{
//读系统注册表中文件类型信息
regVersion = Registry.ClassesRoot.OpenSubKey(fileType, false);
if (regVersion != null)
{
regFileType = regVersion.GetValue("") as string;
regVersion.Close();
regVersion = Registry.ClassesRoot.OpenSubKey(regFileType + @"\DefaultIcon", false);
if (regVersion != null)
{
regIconString = regVersion.GetValue("") as string;
regVersion.Close();
}
}
if (regIconString == null)
{
//没有读取到文件类型注册信息,指定为未知文件类型的图标
regIconString = systemDirectory + "shell32.dll,0";
}
}
else
{
//直接指定为文件夹图标
regIconString = systemDirectory + "shell32.dll,3";
}
string[] fileIcon = regIconString.Split(new char[] { ',' });
if (fileIcon.Length != 2)
{
//系统注册表中注册的标图不能直接提取,则返回可执行文件的通用图标
fileIcon = new string[] { systemDirectory + "shell32.dll", "2" };
}
Icon resultIcon = null;
try
{
//调用API方法读取图标
int[] phiconLarge = new int[1];
int[] phiconSmall = new int[1];
uint count = Win32.ExtractIconEx(fileIcon[0], Int32.Parse(fileIcon[1]), phiconLarge, phiconSmall, 1);
IntPtr IconHnd = new IntPtr(isLarge ? phiconLarge[0] : phiconSmall[0]);
resultIcon = Icon.FromHandle(IconHnd);
}
catch { }
return resultIcon;
}
} /// <summary>
/// 定义调用的API方法
/// </summary>
class Win32
{
[DllImport("shell32.dll")]
public static extern uint ExtractIconEx(string lpszFile, int nIconIndex, int[] phiconLarge, int[] phiconSmall, uint nIcons);
}

【转】 C# ListView实例:文件图标显示的更多相关文章

  1. 解决Chrome关联Html文件图标显示为空白

    用记事本保存为ChromeHTML.reg Windows Registry Editor Version 5.00 [HKEY_CLASSES_ROOT\CLSID\{42042206-2D85-1 ...

  2. 修复TortoiseGit文件夹和文件图标不显示

    原文:http://blog.moocss.com/tutorials/git/1823.html 一. 我的运行环境: 操作系统 Windows 7/8 32bit TortoiseGit (1.7 ...

  3. TortoiseSVN文件夹及文件图标不显示解决方法(兼容Window xp、window7)

    最近遇到TortoiseSVN图标(如上图:增加文件图标.文件同步完成图标等)不显示问题,网上找到的解决方法试了很多都无法真正解决,最后总结了一下,找到了终极解决方案,当然此方案也有弊端,接下来我们就 ...

  4. svn图标显示不正常,文件夹显示但文件不显示svn图标

    svn图标显示不正常,文件夹显示但文件不显示svn图标   这个问题的引发是自己造成的,使用myEclipse时progress会卡在 refresh svn status cache (0%)这里, ...

  5. Eclipse或MyEclipse没有在java类文件上显示Spring图标的问题

    Eclipse或MyEclipse没有在java类文件上显示接口图标的问题解决办法: 前: 后:

  6. Android Studio 那些事|Activity文件前标识图标显示为 j 而是 c

    问题:Activity文件前标识图标显示为 j 而是 c 的图标,或是没有显示,并且自己主动提示不提示 watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/fo ...

  7. Git文件不显示图标/标识

    初次使用Git服务功能,做了很多探路事情,记录下刚刚遇到的问题 情况:安装了Git应用程序,或者也安装了TortoiseGit-1.8.16.0-64bit(类似SVN工具)后,上传下载文件没有问题, ...

  8. SVN检出后文件没有图标显示

    SVN检出后文件没有图标显示   "Win + R"打开运行框,输入"regedit"打开注册表 在注册表编辑界面按"Ctrl + F"快捷 ...

  9. 预装的Office2016,文件图标表显示以及新建失败问题解决 方法

    新购买笔记本电脑,预装的office2016 学生版 启动激活后,会出现文件图标异常, 文件的类型为: ms-resource:Strings/FtaDisplayName.docx (.docx) ...

随机推荐

  1. RobotFrameWork+APPIUM实现对安卓APK的自动化测试----第七篇【元素定位介绍】

    http://blog.csdn.net/deadgrape/article/details/50628113 我想大家在玩自动化的时候最关心的一定是如何定位元素,因为元素定位不到后面的什么方法都实现 ...

  2. MySQL 与 MongoDB的操作对比

    MySQL与MongoDB都是开源的常用数据库,但是MySQL是传统的关系型数据库,MongoDB则是非关系型数据库,也叫文档型数据库,是一种NoSQL的数据库.它们各有各的优点,关键是看用在什么地方 ...

  3. LiquidCrystal库函数

    主要资料来源: 极客工坊-知识库 (LiquidCrystal库地址:http://wiki.geek-workshop.com/doku.php?id=arduino:libraries:liqui ...

  4. 在ActivityA中关闭还有一个ActivityB

    1.对于简单的两个Activity public class A_activity extends Activity { public static A_activity _instance = nu ...

  5. 【C/C++学院】0724-堆栈简单介绍/静态区/内存完毕篇/多线程

    [送给在路上的程序猿] 对于一个开发人员而言,可以胜任系统中随意一个模块的开发是其核心价值的体现. 对于一个架构师而言,掌握各种语言的优势并能够运用到系统中.由此简化系统的开发.是其架构生涯的第一步. ...

  6. VC6 编译和使用 STLPort

    1.下载 STLport:   http://www.stlport.org/   http://downloads.sourceforge.net/project/stlport/STLport/S ...

  7. 树莓派与window 10组成的物联网核心:让人失望

    去年春天,微软公布了自己的window系统与物联网系统的方案,该方案使用树莓派和window 10组成物联网的核心.树莓派是一个与window全然不同的执行在ARM构架下的系统. 是的,也许微软决心离 ...

  8. Tween动画TranslateAnimation细节介绍

    Tween动画有下面这几种: Animation   动画 AlphaAnimation 渐变透明度 RotateAnimation 画面旋转 ScaleAnimation 渐变尺寸缩放 Transl ...

  9. java 顺序 读写 Properties 配置文件 支持中文 不乱码

    java 顺序 读写 Properties 配置文件 ,java默认提供的Properties API 继承hashmap ,不是顺序读写的. 特从网上查资料,顺序读写的代码,如下, import j ...

  10. [C#] 怎样分析stackoverflow等clr错误

    有时候由于无限递归调用等代码错误,w3wp.exe会报错退出.原因是clr.exe出错了. 这样的错误比較难分析,由于C#代码抓不住StackOverflowException等异常. 处理方法是:生 ...