【转】 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. BA-设计施工调试流程

    工程范围 1.楼宇自控系统的工程设计首先要了解目标建筑物所处的地理环境.建筑物用途.楼宇自控系统的建设目标定位.建筑设备规模与控制工艺及监控范围等工程情况.这些情况一般在工程招标技术文件中介绍,设计者 ...

  2. [Tailwind] Create Custom Utility Classes in Tailwind

    In this lesson, we learn how to generate custom utility classes in tailwind. We add new properties t ...

  3. HTML5 Canvas 获取网页的像素值。

    我之前在网上看过一个插件叫做出JScolor   颜色拾取器  说白了就是通过1*1PX的DOM设置颜色值通过JS来获取当前鼠标点击位置DOM的颜色值. 自从HTML5 画布出来之后.就有更好的方法来 ...

  4. cvReadTrainData

    cvReadTrainData的源代码在opencv的cvboost.cpp文件之中,详细内容例如以下所看到的: CV_BOOST_IMPL void cvReadTrainData( const c ...

  5. vi 调到第一行,或最后一行

    用vi命令打开文件直接跳到最后一行的方法如下: :$ 跳到文件最后一行 :0或:1 跳到文件第一行 或 另外一组命令: gg 跳到文件第一行 Shift + g 跳到文件最后一行

  6. 常见问题处理之Emoji

    所谓Emoji就是一种在Unicode位于\u1F601-\u1F64F区段的字符.这个显然超过了目前常用的UTF-8字符集的编码范围\u0000-\uFFFF.Emoji表情随着IOS的普及和微信的 ...

  7. 在Maven中引入spring的DAO、DOMAIN、CONTROLLER、VIEW

    除了mysql外麻雀虽小,五脏俱全. 参照之前的博客建立好的maven项目如图. 第一步 : 向maven项目中的pom文件添加依赖 ,然后maven install

  8. Combo Select – jQuery可搜索下拉框插件

    今天用到另一款jq插件..插件就是无脑,,引入相关文件,开始撸吧 引入相关文件: <link href="~/Scripts/combo-select/combo.select.css ...

  9. TFS源代码管理工具:

    源代码管理: 先获取最新版本,再签入.如发现错误,可以点击--源代码管理--获取特定版本撤回修改 1.签入:(要备注,测试通过后签入) 敏捷开发:(小步快跑):小部分功能开发完成测试通过后就签入 全部 ...

  10. 给SearchView设置样式

    <?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http:/ ...