Reputation: 34760
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,
Upvotes: 0
Views: 246
Reputation: 171421
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.
Upvotes: 1
Reputation: 29632
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.
}
}
Upvotes: 1
Reputation: 54158
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.
Upvotes: 0
Reputation: 85056
Try this:
List<FileInfo> fi = new List<FileInfo>();
//load fi
List<FileInfo> SortedFi = fi.OrderBy(t=>t.CreationTime);
Upvotes: 4