Home > Software design >  Show list from last file to first save
Show list from last file to first save

Time:12-22

I want to reverse the result displayed in a Combobox. The last saved file would appear first, currently it is the opposite. it appears with this code:

string[] files = Directory.GetFiles(@"C:\Test\",*.TXT");

foreach (string file in files)
{
  comboBox1.Items.Add(Path.GetFileNameWithoutExtension(file));
}

According to my research, the solution would be:

.OrderByDescending(p => p.CreationTime).ToArray(); 

added somewhere. But I don't know. Every attempt I've made has been unsuccessful.

Currently:

101-00.06.52.TXT
101-00.06.54.TXT
101-00.06.56.TXT

Desired outcome:

101-00.06.56.TXT
101-00.06.54.TXT
101-00.06.52.TXT

Does anyone know?

CodePudding user response:

Instead of static method Directory.GetFiles() method, use GetFiles() method from DirectoryInfo class. Apply OrderByDescending() on it.


Directory.GetFiles():

Returns the names of files that meet specified criteria

Vs

DirectoryInfo.GetFiles():

Returns a file list from the current directory.


Like,

DirectoryInfo di = new DirectoryInfo(@"C:\Test\"); //Get the Directory information

var allTxtFiles = di.GetFiles("*.txt") //Get all files based on search pattern
     .OrderByDescending(p => p.CreationTime)  //Sort by CreationTime
     .Select(x => x.Name);  //Select only name from FileInfo object

foreach (string file in allTxtFiles)
{
    comboBox1.Items.Add(Path.GetFileNameWithoutExtension(file));
}

CodePudding user response:

I don't know the reason why you problem. But if you want to receive correct result is simple. First try this:

string[] files = Directory.GetFiles(@"C:\Test\",*.TXT");
comboBox1.ItemsSource = files;

if the result is not correct. Use this:

string[] files = Directory.GetFiles(@"C:\Test\",*.TXT");
files = files.Reverse();
comboBox1.ItemsSource = files;
  • Related