first thanks for the help.
I am writing a C# application which to copy some files based on their modification date. The program works for most of the time, except when handling file which is being written by another application. For these files, i realised that the file last modification date will not update until i refresh it manually.
I had the below code to work around, which all the file get refesh first, ensure the modification date is update before i store in the list
DirectoryInfo directory = new DirectoryInfo(@"C:\Testing");
var listofallfile = directory.GetFiles();
var listOfFilesInSpecifiedPeriod = new List<FileInfo>();
foreach (var file in listofallfile)
{
file.Refresh();
if (file.LastWriteTime>= fromDate && file.LastWriteTime <= toDate)
{
listOfFilesInSpecifiedPeriod.Add(file);
}
}
But i would like to have a more simple lines express that. Is there a way to refrest the file modifcation date in the code below?
DirectoryInfo directory = new DirectoryInfo(@"C:\Testing");
var listOfFilesInSpecifiedPeriod = directory.GetFiles()
.Where(file => file.LastWriteTime >= fromDate && file.LastWriteTime <= toDate);
Thanks
You can use the forEach function of the list. It's not on IEnumerable
but it does the trick:
var listOfFilesInSpecifiedPeriod = directory.GetFiles().ToList();
listOfFilesInSpecifiedPeriod.forEach(file => file.Refresh());
listOfFilesInSpecifiedPeriod = listOfFilesInSpecifiedPeriod.Where(file => file.LastWriteTime >= fromDate && file.LastWriteTime <= toDate).ToList();