Hi guys,

I need to sort an array by date created.

Please take a look at this code thus far

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace listboxarraysortexample
    public partial class Form1 : Form

        string[] dirs;

        public Form1()

        private void button1_Click(object sender, EventArgs e)
            dirs = Directory.GetFiles("C://jpegs");

            foreach (string file in dirs)
                string filename = Path.GetFileName(file);


Before I add the items to the list box I want it to build the string array in accordance with teh file create date which the directory info collects.

I realise Im not the best coder in the world however I usually manage to find away, but this beats me. I have tried various appraoches like using the icomparer but none of the example code I looked at help me out.I know that the answe is proabably really easy, can anyone help me?

Thank you in advance

Use this to get an array of FileInfo objects and then sort the array on FileInfo.CreationTime

System.IO.DirectoryInfo di = new System.IO.DirectoryInfo("C:\\jpegs");
System.IO.FileInfo[] files = di.GetFiles();

You can use this to do the sort.

    delegate(FileInfo file1 ,FileInfo file2)
        if (file1 == null)
            if (file2 == null)
                return 0;
                return -1;
            if (file2 == null)
                return 1;
                return file1.CreationTime.CompareTo(file2.CreationTime);

OK thanks Nick.crane, but finally how to I load my string[] with the sorted filenames in the (fileinfo)files[] collection?

i would have thought it was:

string[] dirs = files.toarray();

This dosnt work though! what am i doing wrong? I need to laod my string[] with the sorted filenames so that I can add them to the listbox and they will appear in date order, thanks again in advance much appreciated.

files is already an array. Just add the FileInfo objects to the list box. listBox1.Items.AddRange(files); Note: To reference the listbox items you will need to cast the object type back to an FileInfo object.
E.g. ((FileInfo)listBox1.Items[0]).FullName Edit: To have the listbox contain the filename as a string just modify your original foreach loop

foreach (FileInfo fi in files)

OK I have added the code here. Once i add the files to the listbox they are not in date created order , but the order has certainly changed.

In this screenshot....frame0 was the first written, and they go up from there, frame17 being the file with the mos recent date created stamp.

You can click on the image to get a close look.


Any ideas?

thank you nick its working now!