Filter DirectoryInfo files by date in asp.net

2019-04-11 06:22发布

I am populating a datagrid control using files in a specified path (DirectoryInfo).
I would like to filter the files based on a user specified date range (start date & end date).

While search S/O, I found this post, but I am getting an error on DateComparer ("'DateComparer' is a type and cannot be used as an expression.")

Any other suggestions on how to filter by date?

Here is my code:

        Dim dirInfo As New DirectoryInfo(strDirectoryPath)
        Dim dStartDate As DateTime = "03/01/2011"
        Dim dEndDate As DateTime = "6/30/2011"
        Dim Files As FileInfo = dirInfo.GetFiles().Where(Function(Files) Files.CreationTime >= (dStartDate) AndAlso Files.CreationTime <= dEndDate)

            datagrid.DataSource = Files
            datagrid.DataBind()

1条回答
smile是对你的礼貌
2楼-- · 2019-04-11 07:01
DateTime your_start_date = new DateTime(2011,1,1);
DateTime your_end_date = new DateTime(2011,10,1);
FileInfo [] files = new DirectoryInfo(@"c:\").GetFiles().Where(x=>x.CreationTime>=(your_start_date) && x.CreationTime<=(your_end_date)).ToArray();

foreach(var item in files)
{
 Console.WriteLine(item.Name);
}

On my test case prints out:

copy_one.jpg
copy_one_one.jpg
copy_one_one_one.jpg
hiberfil.sys
one.jpg
pagefile.sys
PcapDotNet.snk

UPDATE (VB version):

Dim your_start_date As New DateTime(2011, 1, 1)
Dim your_end_date As New DateTime(2011, 10, 1)
Dim files As FileInfo() = New DirectoryInfo("c:\").GetFiles().Where(Function(x) x.CreationTime >= (your_start_date) AndAlso x.CreationTime <= (your_end_date)).ToArray()

For Each item As FileInfo In files
    Console.WriteLine(item.Name)
Next
查看更多
登录 后发表回答