简体   繁体   中英

Image Viewer removing items from listbox that not image

I have this code

var dirInfo = new DirectoryInfo(currentDir);
DirectoryInfo di = dirInfo;
FileInfo[] fia = di.GetFiles();
FileInfo t = null;
for (int p = 0; p <= fia.Length - 2; p++)
{
  for (int i = 0; i <= fia.Length - 2; i++)
  {
    if (fia[i].LastWriteTime < fia[i + 1].LastWriteTime)
    {
      t = fia[i + 1];
      fia[i + 1] = fia[i];
      fia[i] = t;
    }
  }
}
foreach (FileInfo fi in fia)
{
  listBoxImages.Items.Add(fi.Name);
}

It's sorting files before adding to ListBox by writing time, but it's wont able to remove files that not an images, before adding it to ListBox. I've tried many solutions that I've googled and nothing worked for me.

Okay, i've found and used this:

 FileInfo[] fia = di.GetFiles("*.bmp")
 .Union(di.GetFiles("*.jpg"))
 .Union(di.GetFiles("*.png"))
 .Union(di.GetFiles("*.jpeg"))
 .Union(di.GetFiles("*.tiff"))
 .ToArray();

so the code looks like:

var dirInfo = new DirectoryInfo(currentDir);
DirectoryInfo di = dirInfo;
FileInfo[] fia = di.GetFiles("*.bmp")
 .Union(di.GetFiles("*.jpg"))
 .Union(di.GetFiles("*.png"))
 .Union(di.GetFiles("*.jpeg"))
 .Union(di.GetFiles("*.tiff"))
 .ToArray();
FileInfo t = null;
for (int p = 0; p <= fia.Length - 2; p++)
{
  for (int i = 0; i <= fia.Length - 2; i++)
  {
    if (fia[i].LastWriteTime < fia[i + 1].LastWriteTime)
    {
      t = fia[i + 1];
      fia[i + 1] = fia[i];
      fia[i] = t;
    }
  }
}
foreach (FileInfo fi in fia)
{
  listBoxImages.Items.Add(fi.Name);
}

beautiful

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM