How can I get the files from the last created directory ?

rhodanny 166 Reputation points
2021-12-20T22:54:11.82+00:00
private void GetImagesFiles()  
        {  
            if (textBoxRadarPath.Text != "" || textBoxSatellitePath.Text != "")  
            {  
                if (Directory.Exists(textBoxRadarPath.Text))  
                {  
                    var t = CheckIfChildFoldersExist(textBoxRadarPath.Text);  
  
                    if (t != null)  
                    {  
                        filesRadar = System.IO.Directory.GetFiles(textBoxRadarPath.Text,  
                                      "*.gif", SearchOption.AllDirectories).OrderBy(x => x).ToArray();  
  
                        Array.Sort(filesRadar, new MyComparer(true));  
                    }  
                }  
  
                if (Directory.Exists(textBoxSatellitePath.Text))  
                {  
                    var t = CheckIfChildFoldersExist(textBoxSatellitePath.Text);  
  
                    if (t != null)  
                    {  
                        filesSatellite = System.IO.Directory.GetFiles(textBoxSatellitePath.Text,  
                                                      "*.gif", SearchOption.AllDirectories).OrderBy(x => x).ToArray();  
  
                        Array.Sort(filesSatellite, new MyComparer(true));  
                    }  
                }  
            }  
        }  

This get the files from all the directories.

In this case the most directory on the right side the last one :

159131-lastdir1.jpg

The way the method is no I'm getting 245 images from all the directories for the radar and about 100 for the satellite images.

but I want to get only from the last directory of the radar and satellite.

Developer technologies | Windows Forms
Developer technologies | C#
0 comments No comments
{count} votes

Accepted answer
  1. P a u l 10,761 Reputation points
    2021-12-20T23:32:24.017+00:00

    You could use DirectoryInfo to get the creation time, order & then just select the first sub-directory. Once you have the directory you can get your files by pattern as you currently are:

    string rootPath = Environment.ExpandEnvironmentVariables(@"%USERPROFILE%\Desktop");
    
    DirectoryInfo directory = new DirectoryInfo(rootPath).GetDirectories()
        .OrderByDescending(d => d.CreationTimeUtc)
        .First();
    
    FileInfo[] files = directory.GetFiles("*.gif");
    

    You're getting all files in all folders because you're passing SearchOption.AllDirectories to GetFiles on the root folder which will return files past the top folder level.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.