When I come across a coding "challenge" like this, I'm always looking to see ... assuming I think I'll be using similar code for similar purposes in the future ... if I can create a small "tool", and, in fact, I have written code for this task in the past.
Here's a "sketch" of how, given a valid Directory-path you can find the last, or first, file created, or modified (last written-to). I omit code to find the last (or first) Directory, since that's so easy to do, and I think you already know how to do that.
This "incomplete sketch" will compile, and get you the first created or modified file in a Directory. You can have the challenge/pleasure of extending it to return last created, or modified:
public enum GetDateBy
{
FirstCreated,
LastCreated,
FirstModified,
LastModified
}
private const string SearchAllString = ".";
public FileInfo GetFileDateBy(string directoryPath, bool recursive, GetDateBy datebyType)
{
if(! Directory.Exists(directoryPath)) throw new ArgumentException("invalid directory path");
var files = new DirectoryInfo(directoryPath).EnumerateFiles(
SearchAllString,
(recursive)
? SearchOption.AllDirectories
: SearchOption.TopDirectoryOnly
);
if (files.Count() == 0) return null;
switch (datebyType)
{
case GetDateBy.FirstCreated:
return files.OrderBy(f => f.CreationTime).First();
case GetDateBy.LastCreated:
break;
case GetDateBy.FirstModified:
return files.OrderBy(f => f.LastWriteTime).First();
case GetDateBy.LastModified:
break;
}
return null;
}
A test of this code ... assume you have a TextBox named 'textBox1 on a Form with its 'MultiLine property set to 'true:
private string format = "'Date:'MM/dd/yyyy\r\n'Time: 'H:mm:ss 'milliseconds: ' FFFFFFF\r\n'UTC: ' zzz";
string filepath = @"C:\Users\YourUserName\Desktop\SomeOuterFolder\SomeInnerFolder";
var f1 = GetFileDateBy(filepath, false, GetDateBy.FirstCreated);
if (f1 != null)
{
f1.Refresh();
textBox1.AppendText(string.Format("file first created: {0}\r\n{1}\r\n\r\n",f1.Name,f1.CreationTime.ToString(format)));
}
var f3 = GetFileDateBy(filepath, false, GetDateBy.FirstModified);
if (f3 != null)
{
f3.Refresh();
textBox1.AppendText(string.Format("file first modified\r\n{0}\r\n{1}\r\n\r\n",f3.Name,f3.LastWriteTime.ToString(format)));
}
Note:
a. why use an Enum here ? I just plain
like Enums, and feel they make code more readable/maintainable/expressive-of-intent, and, many times, easier to extend.
b. this method returns a FileInfo ... or ... null
c. re use of 'EnumerateFiles rather than 'GetFiles: 'EnumerateFiles may be more efficient in some cases. There's a very good CodeProject article that explores/documents this: [
^].
d. you could re-write this as a static extension method, easily.
e. wonder why the LastAccessTime.Millisecond vale is some odd value, or #0: well, so do other people: [
^].
f. note the use of the 'Refresh method on the FileInfo instance here: this is to ensure the file system manager has refreshed FileInfo instances it has cached: [
^].