Click to See Complete Forum and Search --> : [RESOLVED] Get last 7 days files from a folder
remya1000
06-07-2007, 11:12 AM
i need to get only last 7days files from a folder. using vb.net.
in my C drive i have a folder called LogFiles, and inside that logfiles folder i have more than 15-25 log files were there. and the name of each file will be the date in which it created.
eg: 20070607.log (this file created today).
eg: 20070503.log (created last month 3rd).
so i need to get the last 7 days log file by checking with current date.
how can i find the last 7days files from this folder. if you have any idea how to do this please let me know. if example is there, it will be very helpful to me.
thanks in advance.
lmf232s
06-07-2007, 11:24 AM
This is just an idea and there might be a method in system.IO that allows you to only retrun a cretian file. I would look at the name space your using to iterate the directory.
You could create an array/list of all the files that you need.
This is just off the top of my head.
Create a loop that gets iterated 7 times.
With in that loop build the file name by splitting the date into YYYY, MM, DD and using DatePart and DateAdd to get the correct dates.
(Here is a little spaghetti code of what i had in mind)
For i = 0 to 7
sFileName(i) = YYYY & MM & DD & ".log"
Next
Your list should end up looking like this
20070607.log
20070507.log
20070407.log
20070307.log
etc...
Now as your iterating the directory of files. Compare the fileaname to the valid file names (your list you created). If its a valid file then grab it.
If ValidFileName(IOFileName) Then
'Grab File
End If
Function ValidFileName(ByVal sFileName) as Boolean
'Make sure that sFileName = to a filename you have in your list
If so then
Return True
else
Return False
End If
End Function
remya1000
06-07-2007, 12:34 PM
Thanks for the help. as you said i used IO.FileInfo. really thanks for the help.
Dim FileDate As DateTime
Dim intdiff As Integer
Dim i As Integer
Dim di As New IO.DirectoryInfo("C:\LogFiles")
Dim aryFi As IO.FileInfo() = di.GetFiles("*.log")
Dim aFile As ArrayList
Dim fi As IO.FileInfo
For Each fi In aryFi
Dim gname, gname1 As String
gname = fi.Name
gname1 = gname.Substring(0, 8)
FileDate = System.DateTime.ParseExact(gname1, "yyyyMMdd", System.Globalization.DateTimeFormatInfo.InvariantInfo).ToString("MM/dd/yyyy")
intdiff = DateDiff(DateInterval.Day, FileDate, Now)
If intdiff < 7 Then
aFile.Add(gname)
'MessageBox.Show(fi.Name)
End If
Next
For i = 0 To aFile.Count - 1
Dim name As String
name = aFile(i).ToString()
MessageBox.Show(name)
Next
End Sub