tags:

views:

36

answers:

4

I want to keep a list of existing log files from the log directory. whenever this list reached the max limitation, say 20 files, I will delete the oldest log file.

Each time when application is launched, it will check the log directory and keep all log file names in a list. but this list should be sorted with the creation time.

what's the good way to do this? thanks,

+4  A: 

Try this:

List<FileInfo> fi = new List<FileInfo>();
//load fi
List<FileInfo> SortedFi = fi.OrderBy(t=>t.CreationTime);
Abe Miessler
A: 
using System.Linq;
using System.IO;

DirectoryInfo di = new DirectoryInfo("mylogdir");
FileSystemInfo[] files = di.GetFileSystemInfos();
var orderedFiles = files.OrderBy(f => f.CreationTime);

Cache orderedFiles, and refresh as needed whenever you roll over to the next.

Steve Townsend
+1  A: 

Something like this:

static void Main(string[] args)
{
    var files = new List<string>();

    foreach (var file in Directory.GetFiles("<path to your log files>"))
    {
        files.Add(file);
    }

    files.Sort(
        new Comparison<string>(
            (a, b) => new FileInfo(b).CreationTime.CompareTo(new FileInfo(a).CreationTime)
        )
    );

    foreach (var file in files.Skip(20))
    {
        // Delete file.
    }
}
Pieter
+1  A: 

This grabs all the files older than the newest 20 and deletes them:

int numberOfFilesToKeep = 20;
string logFilePath = @"c:\temp";
FileInfo[] logFiles = (new DirectoryInfo(logFilePath)).GetFiles();
var oldFiles = logFiles.OrderByDescending(t => t.CreationTime).Skip(numberOfFilesToKeep);
foreach (var file in oldFiles)
    file.Delete(); //you'll want a try/catch here

Note, you may want to use LastWriteTime rather than CreationTime above, depending upon how the log files are being used.

RedFilter