Search for a file from a folder

I am currently using below code to find next file from folder. Basically I store the last modified date and time of the file I read, and after I have finished processing that file, I need to move on to the next file. But my code currently takes about 10 seconds to find the next file using the code below.

Can anyone 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;
    }
}

      

+3


source to share


1 answer


Have you tried to cache your results. You do most of the work once and then quickly access the results, for example. vocabulary.

Collect time for all 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 looking for all the files again, you simply access the values ​​already collected:

var myFile = filesAndTimes.FirstOrDefault(item => item.Key > lastfile);

      

Also, if you need to update the time for files, you simply add an entry to the dictionary. Note what DateTime

is the key in the dictionary. If it wasn't for the recording time, it could have led to key collisions. But no two write times are the same for two files, so it should be safe to rely on here DateTime

.

+2


source







All Articles