Adrian Brown
Adrian Brown

Reputation: 133

Search a directory for files created between two dates

I am trying to search for all files in a specified folder, which were created between two dates.

The dates are selected from two datetimepickers.

I found this for C#:

var directory = new DirectoryInfo(your_dir);
var files = directory.GetFiles()
.Where(file => file.LastWriteTime >= DateTimePicker1
&& file.LastWriteTime <= datetimerpicker2);

Which I have changed to:

Dim Directory = New DirectoryInfo("C:\Test")
Dim path As String
path = (TextBox1.Text)
Dim files = Directory.GetFiles().Where(File.GetLastWriteTime(path) >= DateTimePicker1 And File.GetLastWriteTime <= datetimerpicker2)

I am obviously getting some syntax etc wrong.

The results (file path and name) will be posted to Listbox1. I would also like to be able to open the file path by clicking on its Listbox entry but that's something I haven't started to look into.

Any ideas for a solution in VB.NET?

Upvotes: 1

Views: 1775

Answers (3)

dbasnett
dbasnett

Reputation: 11773

How about this

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim path As String = TextBox1.Text
    LoadListBox(path)
End Sub

Private csvFiles As List(Of String)
Private Sub LoadListBox(path As String)
    Dim di As New IO.DirectoryInfo(path)
    di.EnumerateFiles("*.*", IO.SearchOption.AllDirectories)
    csvFiles = (From csv In di.EnumerateFiles("*.*", IO.SearchOption.AllDirectories)
                Where csv.CreationTime.Date >= DateTimePicker1.Value.Date AndAlso
                 csv.CreationTime.Date <= DateTimePicker2.Value.Date
                 Select csv.FullName).ToList

    ListBox1.DataSource = csvFiles

End Sub

Upvotes: 0

Adrian Brown
Adrian Brown

Reputation: 133

Using Tim Schmelter's help, I got the desired result using;

    ListBox1.Items.Clear()
    Dim csvFiles = From csv In Directory.EnumerateFiles(TextBox1.Text, "*.*", IO.SearchOption.AllDirectories)
                   Where File.GetCreationTime(csv).Date >= DateTimePicker1.Value AndAlso File.GetCreationTime(csv) <= DateTimePicker2.Value

    For Each csvPath In csvFiles
        ListBox1.Items.Add(csvPath)
    Next

End Sub

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460068

You have to use the DateTimePicker.Value property. Also use VB.NET instead of C# syntax:

Dim files = From file in directory.EnumerateFiles()
            Where file.LastWriteTime >= DateTimePicker1.Value AndAlso file.LastWriteTime <= Datetimerpicker2.Value 

Upvotes: 4

Related Questions