the_farmer
the_farmer

Reputation: 669

How to get last created folder with RootDirInfo.GetDirectories().Where(filter)?

I have the bellow function that works greate but is there away to do that with filter ?

I am looking for something like :

RootDirInfo.GetDirectories().Where(x => x.CreationTime >= Max(x.CreationTime)); 

My function :

public static DirectoryInfo GetLastCreatedDir(string BasePath)
        {
            //string LastCreatedDirName = string.Empty;
            DateTime LastDate = new DateTime(1980, 01, 01);
            DirectoryInfo RootDirInfo = new DirectoryInfo(BasePath);
            DirectoryInfo LastDirInfo = null;

            //Get last Created Owners Idx Folder (by date) 
            foreach (DirectoryInfo InnerDirInfo in RootDirInfo.GetDirectories())
            {
                if (DateTime.Compare(InnerDirInfo.CreationTime, LastDate) > 0)
                {
                    LastDirInfo = InnerDirInfo;
                    LastDate = InnerDirInfo.CreationTime;
                    //LastCreatedDirName = InnerDirInfo.Name;
                }
            }
            return LastDirInfo;
        }

Upvotes: 0

Views: 142

Answers (2)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112344

You can get the most recent directory like this

DirectoryInfo mostRecentDir = RootDirInfo.GetDirectories()
    .OrderByDescending(d => d.CreationTime)
    .FirstOrDefault();

Upvotes: 1

Tigran
Tigran

Reputation: 62246

May be something like:

var mostRecentDirInfo = dirfo.GetDirectories().
                          OrderByDescending(d=>d.CreationTime).Take(1);
  • sort collection of directories by descending based on CreationTime
  • pick the first one in sorted collection

Upvotes: 1

Related Questions