-2

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.

LarsTech
  • 80,625
  • 14
  • 153
  • 225
  • first thing first :) why so many for loops ? and with regards to your question is it ok to filter by image extension/s beforehand ? – jmvcollaborator Sep 07 '22 at 23:22
  • Actually, this is not exactly my code, I borrowed it from one of the local topics on a similar topic and adapted it to work in my application, this is for the question of why there are so many for-loops. BTW, this answers the second question as well, I just didn't try to filter the files before sorting them. I'll try it and respond about results. – user19945067 Sep 07 '22 at 23:29
  • Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. – Community Sep 08 '22 at 10:37

1 Answers1

0

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