Reputation: 57
Currently I am using below code to find the next file from a folder. Basically I store the last modified date and time of a file I read and after i am done processing that file I need to go to the next file. But my code currently takes around 10 sec to search the next file using below code.
Can someone suggest a faster way?
DateTime lastfile = DateTime.Parse(System.IO.File.ReadAllText(@"lastFile.txt"));
string[] systemAFiles = System.IO.Directory.GetFiles("G:\\");
foreach (string files in systemAFiles)
{
DateTime lastWriteTime = System.IO.File.GetLastWriteTime(files);
if (lastWriteTime > lastfile) //produced after last file was read
{
readxml(files);
break;
}
}
Upvotes: 3
Views: 142
Reputation: 8782
Did you try to cache your results. You perform bulk of the work once and then quickly access the results from e.g. dictionary.
Collect times for all the files:
string[] systemAFiles = System.IO.Directory.GetFiles("G:\\");
Dictionary<DateTime, string> filesAndTimes = new Dictionary<DateTime, string>();
foreach (string file in systemAFiles)
{
var time = System.IO.File.GetLastWriteTime(file);
filesAndTimes[time] = file;
}
And then, instead of searching all files again, you just access already collected values:
var myFile = filesAndTimes.FirstOrDefault(item => item.Key > lastfile);
Also, if you need to update times for the files you just add an entry to the dictionary. Note, that the DateTime
is a key in the dictionary. If it were not the write time it could result in key clashes. But there are no two identical write times for two files so it should be safe to rely on DateTime
here.
Upvotes: 2