tags:

views:

1381

answers:

5

Hello everyone,

I am using VSTS 2008 + C# + .Net 3.0. I want to enumerate all files in a directory by creation time, i.e. files created more recently will be enumarate at first, files created for a long time (older) will be enumerated at last. Any ideas how to implment this?

thanks in advance, George

+2  A: 

I would probably use LINQ and a list... something like this should work:

 DirectoryInfo di = new DirectoryInfo("YourPath");
 List<FileInfo> files = di.GetFiles().OrderBy(f => f.CreationTime).ToList();

 foreach (FileInfo file in files)
        {
            //do something
        }
Robban
Sorry I am using .Net 3.0, can not use LINQ. Any .Net 3.0 based solution?
George2
+4  A: 

Something like that


System.IO.FileInfo[] array = new System.IO.DirectoryInfo("directory_path").GetFiles();
Array.Sort(array, delegate(System.IO.FileInfo f1, System.IO.FileInfo f2)
            {
                return f2.CreationTimeUtc.CompareTo(f1.CreationTimeUtc);
            });

Tadas
Don't you have to revert the order to have more recent files first as asked ?
Cédric Rup
Cédric, you are right. Thanks.
Tadas
Second point : with VS2008, you can use lambdas, even in 2.0 or 3.0 ! Makes it easier to read... but you can use them only if your build process uses MsBuild 3.5 (mind the CI server for example...)
Cédric Rup
Oh, and the "var" keyword too ;o)
Cédric Rup
Your solution works!
George2
+1  A: 

Try somithing like this:

DirectoryInfo di = new DirectoryInfo("path to folder");
FileInfo[] files = di.GetFiles();
IOrderedEnumerable<FileInfo> enumerable = files.OrderBy(f => f.CreationTime);

foreach (FileInfo info in enumerable)
{
  // do stuff...     
}
ema
Sorry I am using .Net 3.0, can not use LINQ. Any .Net 3.0 based solution?
George2
A: 
DirectoryInfo baseFolder=new DirectoryInfo("folderName");
FileInfo[] files=baseFolder.GetFiles("");
for(int i=1; i<=files.Length;i++)
for(int j=1; j<files.Length;j++)
{
    if(files[j].CreationTime > files[j+1].CreationTime)
    {
     FileInfo f = files[j];
     files[j] = files[j+1];
     files[j+1] = f;
    }
}
x2
I don't see the point of rewriting everything as the framework has a lot of stuff to order collections !
Cédric Rup
+1  A: 

EDIT: updated, here's a non-LINQ solution

FileInfo[] files = new DirectoryInfo("directory").GetFiles();
Array.Sort(files, delegate(FileInfo f1, FileInfo f2) {
    return f2.CreationTime.CompareTo(f1.CreationTime);
});

The above will sort by latest to oldest. To sort by oldest to latest change the delegate to: return f1.CreationTime.CompareTo(f2.CreationTime);


LINQ solution:

FileInfo[] files = new DirectoryInfo("directory").GetFiles();
var results = files.OrderByDescending(file => file.CreationTime);

Use OrderByDescending to sort by most recent CreationTime, otherwise use OrderBy to sort from oldest to newest CreationTime.

Ahmad Mageed
Added a non-LINQ solution based on your comment to another answer
Ahmad Mageed