StumbleUpon
Share on Facebook

Thursday, January 29, 2009

C# GetFiles with Date Filter

How to Filter files that are modified in a specific day using C#

Here is a snippet using C# and LINQ, which will retrieve the files from a directory for a specific date

private static void GetFilesFromDirectory(string DirPath)

{

try

{

DirectoryInfo Dir = new DirectoryInfo(DirPath);

FileInfo[] FileList = Dir.GetFiles("*.*", SearchOption.TopDirectoryOnly );

var query = from FI in FileList

where FI.LastWriteTime.Date == DateTime.Now.Date

select FI.FullName + " " + FI.LastWriteTime;

foreach (string s1 in query )

{

Console.WriteLine(s1);

}

}

catch (Exception ex)

{

Console.WriteLine(ex.Message );

}

}



1 comment:

Amy Liu said...

public int Compare(object x, object y)
{
FileInfo File1 = default(FileInfo);
FileInfo File2 = default(FileInfo);
File1 = (FileInfo)x;
File2 = (FileInfo)y;
return (DateTime.Compare(File1.LastWriteTime, File2.LastWriteTime))*(-1);
}

after you get all the files in the directory, use array sort. below is the code:

DirectoryInfo dirinfo = default(DirectoryInfo);
FileInfo[] allFiles = null;
dirinfo = new DirectoryInfo(strArtworkDirectory);
allFiles = dirinfo.GetFiles();

Array.Sort(allFiles, new clsCompareFileInfo()); // this sort file by modified date desc
dirinfo = null;

//int count = 0; //test for the break --it works
foreach (FileInfo fi in allFiles)
{

if (fi.LastWriteTime > DateTime.Today.AddHours(-2))
{
//Console.WriteLine(fl.FullName.ToString());
///do sth.

}
else
break;
////count = count + 1;
}

allFiles = null;
dirinfo = null;

Related Posts Plugin for WordPress, Blogger...