c# List files in a directory

The below code is written in C# and will write out to console what files are stored under a given directory that were last modified before a given number of days.
first things first, add the below declaration: –

using System.IO;

Now, You can hard code a path in, or you can provide a path on an argument. Below is the Void I use, it can be called from another Void (chaining, which I don’t like doing), or from the main void: –

private static void GetFilesFromDirectory(string DirPath)
{
try
{
DirectoryInfo Dir = new DirectoryInfo(DirPath);
FileInfo[] FileList = Dir.GetFiles(“*.*”, SearchOption.AllDirectories);
var query = from FI in FileList where FI.LastWriteTime.Date == DateTime.Now.Date.AddDays(-3) select FI.FullName + ” ” + FI.LastWriteTime;
foreach (string s1 in query )
{
Console.WriteLine(s1);
}
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message );
Console.ReadLine();
}
}

You can call this function using the below code: –
GetFilesFromDirectory(args[0]);

Alternatively, you can run it with a hardcoded path: –
GetFilesFromDirectory(@”C:\temp”);

A little explanation, the query line can be amended to suit your needs, you can change the ‘AddDays(-3)’ to whatever you feel is best for you. changing this will search for files that were last modified within the last given number of days.
The ‘Foreach’ loop will search through each entry that matches the criteria and write it to the console.
The line that reads ‘Console.ReadLine()’ will leave everything in the console window until you press return.

Leave a Reply