Reputation: 11319
First I'm getting the last folder (3) then I want to get the folder before it (2) but in my code it's getting the first folder (1) and I want to get (2).
var lastWrittenFolder = new DirectoryInfo(textBoxPath.Text).GetDirectories()
.OrderByDescending(d => d.LastWriteTimeUtc).First();
var firstWrittenFolder = new DirectoryInfo(textBoxPath.Text).GetDirectories()
.OrderBy(d => d.CreationTimeUtc).First();
var F = Directory.GetFiles(lastWrittenFolder.FullName, "*.gif").Last();
var LF = Directory.GetFiles(firstWrittenFolder.FullName, "*.gif").Last();`
the variable names are wrong I will fix it but I want instead firstWrittenFolder that it will be : writenFolderBeforeLast so in the end I will get the last file of the last folder and the last file in the folder before.
This :
var firstWrittenFolder = new DirectoryInfo(textBoxPath.Text).GetDirectories()
.OrderBy(d => d.CreationTimeUtc).First();
Should get the folder before :
var lastWrittenFolder = new DirectoryInfo(textBoxPath.Text).GetDirectories()
.OrderByDescending(d => d.LastWriteTimeUtc).First();
and in the end to check first if there are more then 1 folders because then it should not get the one before because it will not be exist yet.
I tried the code above but getting the first folder instead the one before the last. I want to get the last file from the last folder and the last file from the folder before the last.
Upvotes: 0
Views: 193
Reputation: 186668
Please note, that GetDirectories()
returns you an array which you can easily play with:
// We have an array as the result:
DirectoryInfo[] allDirs = new DirectoryInfo(textBoxPath.Text).GetDirectories();
// After sorting the array, we can easily get...
Array.Sort(allDirs, (a, b) => a.LastWriteTimeUtc.CompareTo(b.LastWriteTimeUtc));
// ... its first item
var firstWrittenFolder = allDirs.Length > 0 ? allDirs[0] : default;
// ... second from the end item
var beforeLast = allDirs.Length > 1 ? allDirs[allDirs.Length - 2] : default;
// Files within the second last directory
if (allDirs.Length > 1) {
var files = allDirs[allDirs.Length - 2].GetFiles();
...
}
Addressing IO can well be time consuming, we should avoid calling .GetDirectories()
too often, that's why we do it once, get an array and then
work with this array only.
Upvotes: 0
Reputation: 1
You can get the second last folder like and the last file from it using the below logic.
var folders = new DirectoryInfo(textBoxPath.Text).GetDirectories()
.OrderByDescending(d => d.LastWriteTimeUtc);
if (folders.Count() > 1)
{
var writtenFolderBeforeLast = folders.Skip(1).Take(1).First();
var lastFileInFolderBeforeLast = Directory.GetFiles(writtenFolderBeforeLast.FullName, "*.gif").Last();
}
Upvotes: 2