user1269592
user1269592

Reputation: 701

Choose the newest file from each directory

I am using this to choose a root folder and take the newest file from each directory before adding this files into my listbox but in some cases it does not choose the newest file.

var rootDirFile = Directory
    .EnumerateFiles(pathToSearch, "*.doc", SearchOption.TopDirectoryOnly)
    .OrderByDescending(f => File.GetLastWriteTime(f))
    .Take(1);

var allNewestFilesOfEachFolder = Directory
    .EnumerateDirectories(pathToSearch, "*.*", SearchOption.AllDirectories)
    .Select(d => Directory.EnumerateFiles(d, "*.doc")
        .OrderByDescending(f => File.GetLastWriteTime(f))
        .FirstOrDefault());

foreach (string tempFile in rootDirFile.Concat(allNewestFilesOfEachFolder))
{
    //add the file
}

Upvotes: 0

Views: 178

Answers (3)

paul
paul

Reputation: 22001

This should give you a list of directory/latest file pairs:

var latestByDirectory = new DirectoryInfo(_strPath)
    .GetDirectories()
    .Select(d => new
    {
         Directory = d,
        LatestFile = d.GetFiles()
            .OrderByDescending(f => f.CreationTime)
            .DefaultIfEmpty((FileInfo)null)
            .ToList().First()
    });

Upvotes: 0

E.T.
E.T.

Reputation: 944

We've been using this for a while and don't seem to have any problems.

We can't use File.GetCreationTime since edits are made in files regardless of creation time.

while (Directory.GetFiles(dir, "*", SearchOption.TopDirectoryOnly).Count() > 7)
  {
     DirectoryInfo dirInfo = new DirectoryInfo(dir);
     FileSystemInfo fileInfo = dirInfo.GetFileSystemInfos().OrderBy(fileT => fileT.LastWriteTime).First();
     File.Delete(fileInfo.FullName);
  }

Upvotes: 0

Tigran
Tigran

Reputation: 62246

File.GetLastWriteTime Is not always reliable on WindowsVista/7 (see my answer in this post) as it could seem.

To create more reliable solution, you may use think about FileSystemWatcher, but in that case you would need to use some kind of running service.

Or can think about use if File.GetCreationTime, if that "new" files are actually created every time.

Upvotes: 1

Related Questions