仅显示列表框中的图像文件扩展名

时间:2013-02-12 20:17:57

标签: c# winforms file listbox image

是否可以显示列表框内容,只显示某些具有特定格式的文件?与BMP|*.bmp|GIF|*.gif|JPG|*.jpg;*.jpeg|PNG|*.png|TIFF|*.tif;*.tiff一样,只有具有这些扩展名的文件我想在lstFiles列表框中显示。

我试过了,

lstFiles.Filter = "BMP|*.bmp|GIF|*.gif|JPG|*.jpg;*.jpeg|PNG|*.png|TIFF|*.tif;*.tiff";

但这不起作用,有可能吗?

编辑:

我有三个联合列表框来显示系统驱动器,文件夹及其内容

private void lstDrive_SelectedIndexChanged_1(object sender, EventArgs e)
        {
            lstFolders.Items.Clear();

            try
            {
                DriveInfo drive = (DriveInfo)lstDrive.SelectedItem;

                foreach (DirectoryInfo dirInfo in drive.RootDirectory.GetDirectories())
                    lstFolders.Items.Add(dirInfo);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void lstFolders_SelectedIndexChanged_1(object sender, EventArgs e)
        {
            lstFiles.Items.Clear();

            DirectoryInfo dir = (DirectoryInfo)lstFolders.SelectedItem;

            foreach (FileInfo fi in dir.GetFiles())
                lstFiles.Items.Add(fi);
        }

        private void lstFiles_SelectedIndexChanged(object sender, EventArgs e)
        {
            pictureBox1.Image = Image.FromFile(((FileInfo)lstFiles.SelectedItem).FullName);

        }

        private int lastIndex = 0;

        private void lstFiles_KeyUp(object sender, KeyEventArgs e)
        {

            if (lstFiles.SelectedIndex == lastIndex)
            {
                if (e.KeyCode == Keys.Up)
                {
                    lstFiles.SelectedIndex = lstFiles.Items.Count - 1;
                }

                if (e.KeyCode == Keys.Down)
                {
                    lstFiles.SelectedIndex = 0;
                }

            }

            lastIndex = lstFiles.SelectedIndex;
        }
    }
}

2 个答案:

答案 0 :(得分:2)

您使用FileInfo对象自行填充列表框。 FileInfo有一个属性Extension。您可以使用该过滤进行过滤:

    private void lstFolders_SelectedIndexChanged_1(object sender, EventArgs e)
    {
        lstFiles.Items.Clear();

        DirectoryInfo dir = (DirectoryInfo)lstFolders.SelectedItem;

        foreach (FileInfo fi in dir.GetFiles())
            switch(fi.Extension.ToUpperInvariant())
            {
               case ".BMP":
               case ".JPG":
               ...
                    lstFiles.Items.Add(fi);
                    break;
             }
     }

答案 1 :(得分:0)

好的,我个人不知道也没有听说过在列表框中使用“过滤器”。为什么不在列表中添加所需的项目?

lstFiles.Items.Clear();

List<string> allowedExtensions = new List<string>() {".jpg", ".png", ".gif"};

DirectoryInfo dir = (DirectoryInfo)lstFolders.SelectedItem;

foreach (FileInfo fi in dir.GetFiles().Where((x)=>allowedExtensions.Contains(x)))
{
    lstFiles.Items.Add(fi);
}