【转】 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. 使用Dropzone上传图片及回显演示样例

    一.图片上传所涉及到的问题 1.HTML页面中引入这么一段代码 <div class="row"> <div class="col-md-12" ...

  2. DirectX11 学习笔记10 - 用文件存储顶点布局

    这节须要把顶点布局写在文件中面,为了方便.由于一大串很抽象的坐标放在CPP和程序混在一起很的不方便. 以下全为c++知识,读取文件中面的特定格式的数据: Vertex Count: 36 Data: ...

  3. Dynamics CRM2013 6.1.1.1143版本号插件注冊器的一个bug

    近期在做的项目客户用的是CRM2013sp1版本号,所以插件注冊器使用的也是与之相应的6.1.1.1143,悲剧的事情也因此而開始. 在插件中注冊step时,工具里有个run in user's co ...

  4. 解决ORA-02395:超出I/O使用的调用限制问题

    ORACLE的PROFILE文件是限制数据库用户使用的资源的一种手段.如:控制session或sql能使用的CPU.控制用户的password管理策略等. 数据库创建后,系统则存在名为DEFAULT的 ...

  5. 英语发音规则---M字母

    英语发音规则---M字母 一.总结 一句话总结: 1.M发[m]音? monkey ['mʌŋkɪ] n. 猴子:顽童 come [kʌm] vi. 来 tomato [tə'mɑːtəʊ] n. 番 ...

  6. IPK僵尸网络 看看其传播手法

    转自:http://www.freebuf.com/vuls/154975.html 一.IPK僵尸网络概述 IPK僵尸家族是自2012年底就开始出现并长期持续活跃在境外的DDoS僵尸网络.2016年 ...

  7. numpy的scale就是 x-mean/std

    >>> from sklearn import preprocessing >>> import numpy as np >>> a=np.arr ...

  8. 11. Container With Most Water[M]盛最多水的容器

    题目 Given \(n\) non-negative integers \(a_1,a_2,\cdots,a_n\), where each represents a point at coordi ...

  9. Authrize特性登录验证

  10. 对ListView的Item子控件监听并跳转页面

    public class MyAdapteforOwner extends BaseAdapter{ List<OwnerDevice>datas; private Context con ...