ListView 根据 文件路径 或 扩展名 显示系统文件图标
阅读原文时间:2023年07月10日阅读:1

private void 获取文件button1_Click(object sender, EventArgs e)

        {
            folderBrowserDialog1.ShowDialog();
            string path = folderBrowserDialog1.SelectedPath;

            listView1.View = View.List;
            listView1.Items.Clear();

            DirectoryInfo dir = new DirectoryInfo(path);

            #region 递归遍历文件夹
            foreach (DirectoryInfo dirfolder in dir.GetDirectories())
            {

                listView1.SmallImageList = imageList1;
                listView1.Items.Add(dirfolder.Name, 0);
            }
            #endregion

            #region 递归遍历文件;
            foreach (FileInfo dirfile in dir.GetFiles())
            {
                // listView1.Items.Add(dirfile.Name, 1);
                if (!imageList1.Images.Keys.Contains(dirfile.Extension))
                {
                    imageList1.Images.Add(dirfile.Extension,Icon.ExtractAssociatedIcon(dirfile.FullName));
                }

                ListViewItem lvi = new ListViewItem();
                lvi.Text = dirfile.Name;
                lvi.ImageIndex = imageList1.Images.Keys.IndexOf(dirfile.Extension);
                listView1.Items.Add(lvi);
             }
             #endregion
        }