public void GetListViewItem(string path, ImageList imglist, ListView lv)//获取指定路径下所有文件及其图标
{
lv.Items.Clear();
Win32.SHFILEINFO shfi = new Win32.SHFILEINFO();
try
{
string[] dirs = Directory.GetDirectories(path);
string[] files = Directory.GetFiles(path);
for (int i = 0; i < dirs.Length; i++)
{
string[] info = new string[4];
DirectoryInfo dir = new DirectoryInfo(dirs[i]);
if (dir.Name == "RECYCLER" || dir.Name == "RECYCLED" || dir.Name == "Recycled" || dir.Name == "System Volume Information")
{ }
else
{
//获得图标
Win32.SHGetFileInfo(dirs[i],
(uint)0x80,
ref shfi,
(uint)System.Runtime.InteropServices.Marshal.SizeOf(shfi),
(uint)(0x100 | 0x400)); //取得Icon和TypeName
//添加图标
imglist.Images.Add(dir.Name, (Icon)Icon.FromHandle(shfi.hIcon).Clone());
info[0] = dir.Name;
info[1] = "";
info[2] = "文件夹";
info[3] = dir.LastWriteTime.ToString();
ListViewItem item = new ListViewItem(info, dir.Name);
lv.Items.Add(item);
//销毁图标
Win32.DestroyIcon(shfi.hIcon);
}
}
for (int i = 0; i < files.Length; i++)
{
string[] info = new string[4];
FileInfo fi = new FileInfo(files[i]);
string Filetype = fi.Name.Substring(fi.Name.LastIndexOf(".")+1,fi.Name.Length- fi.Name.LastIndexOf(".") -1);
string newtype=Filetype.ToLower();
if (newtype == "sys" || newtype == "ini" || newtype == "bin" || newtype == "log" || newtype == "com" || newtype == "bat" || newtype == "db")
{ }
else
{
//获得图标
Win32.SHGetFileInfo(files[i],
(uint)0x80,
ref shfi,
(uint)System.Runtime.InteropServices.Marshal.SizeOf(shfi),
(uint)(0x100 | 0x400)); //取得Icon和TypeName
//添加图标
imglist.Images.Add(fi.Name, (Icon)Icon.FromHandle(shfi.hIcon).Clone());
info[0] = fi.Name;
info[1] = fi.Length.ToString();
info[2] = fi.Extension.ToString();
info[3] = fi.LastWriteTime.ToString();
ListViewItem item = new ListViewItem(info, fi.Name);
lv.Items.Add(item);
//销毁图标
Win32.DestroyIcon(shfi.hIcon);
}
}
}
catch
{
}
}
本文介绍了一个使用C#编写的函数,该函数能够获取指定路径下所有文件及文件夹的图标,并将其显示在ListView中。文章展示了如何利用Win32 API来获取文件和文件夹的图标资源。
2482

被折叠的 条评论
为什么被折叠?



