Open all files within Start Date & End Date. - vb.net

I'm trying to open all files within a folder that belong in a date range.
This is what I used so far: This opens all of the files within a folder. But even though I placed a "Marker" so I don't open the files I don't need, I need a more advanced technique...
Dim sFname As String
Dim MyFiles() As String
MyFiles = System.IO.Directory.GetFiles(path, "*_x" & "*.xlsx", IO.SearchOption.AllDirectories)
For Each sFname In myFiles
'And the code to open the files in excel.
I started with this: DateTimePicker1.Value as starting date, Picker2 as ending date.
Dim STDate As String
STDate = DateTimePicker1.Value
Dim EnDate As String
EnDate = DateTimePicker2.Value
I searched for hours, but haven't found anything useful...
Please help.

For Each filePath In Directory.GetFiles("*.xlsx").
Where(Function(s) File.GetCreationTime(s) >= startTime AndAlso
File.GetCreationTime(s) <= endTime)
'Use filePath here.
Next
or
For Each info In New DirectoryInfo(folderPath).GetFiles("*.xlsx").
Where(Function(fi) fi.CreationTime >= startTime AndAlso
fi.CreationTime <= endTime)
Dim filePath = info.FullName
'Use filePath here.
Next

Related

Unable to open txt file path

This code runs perfectly when I hard code the path to the textfile. But as suggested, it is much better not to hard code stuff. I tried it this way and still can't find the txt file even if it exists.
Dim Findstring = IO.File.ReadAllText(Directory.GetCurrentDirectory() + " Redmi03-JCO0531-WX_" + DateTime.Now.ToString("yyyyMMdd") + ".txt")
Dim Lookfor As String = Format(Now, "MM/dd/yyyy HH:mm:ss")
'MessageBox.Show(Findstring.ToString())
showdat.Text = Lookfor
If Findstring.Contains(Lookfor) Then
'MsgBox("Found: " & Lookfor)
For Each prog As Process In Process.GetProcesses
If prog.ProcessName = "Redmi03-JCO0531-WX" Then
prog.Kill()
Process.Start(Directory.GetCurrentDirectory() + "Redmi03-JCO0531-WX.exe")
End If
Next
End If
I guess your problem is at this line
Dim Findstring = IO.File.ReadAllText(Directory.GetCurrentDirectory() + " Redmi03-JCO0531-WX_" + DateTime.Now.ToString("yyyyMMdd") + ".txt")
Let's break that down and see what each part really is.
First at the top of the code file add
Imports System.IO
Then in your Form class
Private Sub OPCode()
Dim dir As String = Directory.GetCurrentDirectory()
MessageBox.Show(dir)
Dim TextFileName = " Redmi03-JCO0531-WX_" & DateTime.Now.ToString("yyyyMMdd") & ".txt"
MessageBox.Show(TextFileName)
Dim CompletePath = Path.Combine(dir, TextFileName)
MessageBox.Show(CompletePath)
Dim Findstring = IO.File.ReadAllText(CompletePath)
End Sub
Actually, you can add a break point and step through the code checking the values of your in your code instead of all these silly Message Boxes. If the 3rd MessageBox does not show the actual location of your file then it is back to the drawing board.
EDIT
Edit to get path on desktop.
Private Sub OPCode()
Dim dir As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
MessageBox.Show(dir)
Dim TextFileName = "ChinaUMS Bank\Redmi05\Redmi03-JCO0531-WX_" & DateTime.Now.ToString("yyyyMMdd") & ".txt"
MessageBox.Show(TextFileName)
Dim CompletePath = Path.Combine(dir, TextFileName)
MessageBox.Show(CompletePath)
' Dim Findstring = IO.File.ReadAllText(CompletePath)
End Sub
Notice that you must hardcode the sub-folders. The special folder will get the Desktop path for the current user.

recursive reading for files in folder using vb.net

I wrote a program which is not checking the file update time but its not checking recursive folder files.kindly help for recursive folder files as well.
My code is here :
Sub getfilestat1()
Dim fileName As String
Dim CurrCyleTime As Date
Dim PrevCycleTime As Date
Dim DBCycleTime As Date
Dim connectionString As String, sql As String
Dim _SQLConnection As AseConnection
Dim _SQLCommand As AseCommand
Dim _SQLAdapter As AseDataAdapter
Dim _DataSet As DataSet
Dim _SQLReader As AseDataReader
_SQLConnection = New AseConnection
_SQLCommand = New AseCommand
_SQLConnection.ConnectionString = "Data Source='10.49.196.97';Port=9713;Database=db_print;Uid=kuat199;Pwd=testing1; "
_SQLCommand.Connection = _SQLConnection
_SQLCommand.CommandText = ""
_SQLCommand.CommandType = CommandType.Text
_SQLCommand.CommandTimeout = 900000000
_SQLConnection.Open()
Dim command As New AseCommand("select * from Kampachi_Cycle", _SQLConnection)
Dim reader As AseDataReader = command.ExecuteReader()
While reader.Read()
' Console.WriteLine(reader("pol_no").ToString() & " " & Convert.ToString(reader("image_return")) & " " & Convert.ToString(reader("no_of_images")))
DBCycleTime = reader("CYCLE").ToString()
End While
' Dim asSettings As AppSettingsSection = cAppConfig.AppSettings
'Dim fi As New System.IO.DirectoryInfo("D:\Vimal\test")
Dim fi As New System.IO.DirectoryInfo("\\kaip3r7ciwf01\BicorData\report\kam\")
Dim files = fi.GetFiles("*", SearchOption.AllDirectories).ToList()
'For Each filename As String In IO.Directory.GetFiles(Directory, "*", IO.SearchOption.AllDirectories)
'For Each file In files Select file Order By file.CreationTime Descending
''Dim first = (From file In files Select file Order By file.CreationTime Ascending).FirstOrDefault
'Count the number files in network path
Dim fcount = files.Count()
'Fetching the previous cycle run time from config file
PrevCycleTime = ConfigurationManager.AppSettings("PrevCycleTime")
CurrCyleTime = Now()
ConfigurationManager.AppSettings("PrevCycleTime") = CurrCyleTime
''''My.Settings.Save()
For i As Integer = 0 To fcount - 1
If files(i).LastWriteTime > DBCycleTime.AddMinutes(-20) Then
fileName = files(i).Name.ToString()
Dim insertCmd As New AseCommand("INSERT INTO Kampachi_FilesProcess " + " ( FILENAME, FileReadStatus) " + " VALUES( #file_name, #read_stat )", _SQLConnection)
Dim parm As New AseParameter("#file_name", AseDbType.VarChar, 1000)
insertCmd.Parameters.Add(parm)
parm = New AseParameter("#read_stat", AseDbType.VarChar, 12)
insertCmd.Parameters.Add(parm)
Dim recordsAffected As Integer
insertCmd.Parameters(0).Value = fileName
insertCmd.Parameters(1).Value = "Y"
recordsAffected = insertCmd.ExecuteNonQuery()
If i = 0 Then
fileName = files(i).Name.ToString()
Dim updCmd As New AseCommand("update Kampachi_Cycle set CYCLE = Getdate()", _SQLConnection)
Dim updparm As New AseParameter("#file_name", AseDbType.VarChar, 1000)
recordsAffected = updCmd.ExecuteNonQuery()
End If
End If
Next
End Sub
After these changes it looks fine and giving out properly.
It is giving recursive reading as well.
Change this line:
Dim files = fi.GetFileSystemInfos.ToList()
To:
Dim files = fi.GetFiles("*", SearchOption.AllDirectories).ToList()
To answer below question about the If not checking all of the files: You are correct, but your code explicitly used the FirstOrDefault method so it would only ever examine the first file. I don't know what you're doing with the rest of your program here, and your question didn't specify, but the above answered your question about recursive file searching.
To get a list of all the files that are older than 25 minutes use this code:
Dim files As List(Of FileInfo) = fi.GetFiles("*", SearchOption.AllDirectories).ToList
Dim oldFileTimeStamp As DateTime = DateTime.Now.AddMinutes(-25)
Dim olderFiles As List(Of FileInfo) = files.Where(Function(fi2) fi2.LastWriteTime > oldFileTimeStamp).ToList()
Please, if this answered this specific question, please click the accepted answer button. If you have additional questions, unrelated to the original question, please open a new Stackoverflow question, and do not add new questions to an existing Stackoverflow question. This makes it easier for future viewers to find answers to your follow up question(s) (ie: search won't find questions inside of question, it only finds the original question).

I have a code that displays oldest file name in a file directory, but how to modify that code so that it shows oldest file date instead of file name?

The below code shows oldest file name in a file directory, but I am interested in knowing the oldest file date, but not the oldest file name.
Sub oldestdate()
Range("G10").Value = GetOldestFile("xxxxx\yyyy\gggggg\uuuuuu")
End Sub
Public Function GetOldestFile(ByVal FileFolder As String, _
Optional ByVal FileMask As String = "*.*", _
Optional ByVal FullName As Boolean = True) As String
Dim FoundFile As String
Dim FileDT As Date
Dim OldestFile As String
Dim OldestDT As Date
Dim FS As Object
'// Get rid of any terminating '\' just to get to a known state
If Right(Trim(FileFolder), 1) = "\" Then
FileFolder = Left(FileFolder, Len(Trim(FileFolder)) - 1)
End If
'// Get First file found in described folder
FoundFile = Dir$(FileFolder & "\" & FileMask)
'// Default return date
OldestDT = Now
Set FS = CreateObject("Scripting.FileSystemObject")
'// Loop through the rest of the files in that folder
Do Until FoundFile = ""
FileDT = FS.GetFile(FileFolder & "\" & FoundFile).DateCreated
'// Compare Current File datetime with oldest found
If FileDT < OldestDT Then
OldestFile = FoundFile
OldestDT = FileDT
End If
'// Get next file
FoundFile = Dir$
Loop
Set FS = Nothing
GetOldestFile = Format(OldestDT, "mm/dd/yyyy")
End Function
Please check the code and let me know if you have any questions or comments.

function to delete folders older than 10 days in vb

I want to create a function which should delete all subfolders of a folder which are 10 days older.
Shell script to delete directories older than n days
I want show all the folder and count how much old and delete if it is 10 days old.
enter code here
Private Function test(ByVal directory As String) As String()
Dim fi As New IO.DirectoryInfo(directory)
Dim path() As String = {}
For Each subfolder As IO.DirectoryInfo In fi.GetDirectories()
Array.Resize(path, path.Length + 1)
path(path.Length - 1) = subfolder.FullName
For Each s As String In test(subfolder.FullName)
Array.Resize(path, path.Length + 1)
path(path.Length - 1) = s
Dim w = IO.Path.GetFileName(s)
'' ListBox1.Items.Add(w)
Dim iDate As String = w
Dim oDate As DateTime = Convert.ToDateTime(iDate)
''MsgBox(oDate.Day & " " & oDate.Month & " " & oDate.Year)
DateTimePicker1.Value = DateTime.Today
Dim date2 As Date = oDate
Dim span = DateTimePicker1.Value - date2
Dim days As Double = span.TotalDays
'' MsgBox(days)
'' ListBox1.Items.Add(days)
Next
Next
this part is not working
If days > 10 Then
fi.Delete()
End If
Iterate through the directory, get each folder's properties, and get the TimeSpan difference from today to the folder's creation date.
Try
Dim dtCreated As DateTime
Dim dtToday As DateTime = Today.Date
Dim diObj As DirectoryInfo
Dim ts As TimeSpan
Dim lstDirsToDelete As New List(Of String)
For Each sSubDir As String In Directory.GetDirectories(sDirectory)
diObj = New DirectoryInfo(sSubDir)
dtCreated = diObj.CreationTime
ts = dtToday - dtCreated
'Add whatever storing you want here for all folders...
If ts.Days > 10 Then
lstDirsToDelete.Add(sSubDir)
'Store whatever values you want here... like how old the folder is
diObj.Delete(True) 'True for recursive deleting
End If
Next
Catch ex As Exception
MessageBox.Show(ex.Message, "Error Deleting Folder", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try

Path not found when creating a file-VBA

I'm trying to create a text file and write data to it, simple right.
Well it's not working and I've looked everywhere for it but can't find an answer.
When it gets to the CreateTextFile() method it throws a path not found error. But I've made sure the path is valid and exists.
'Create a text file
Private Sub OpenFile()
Dim filePath As String
Dim fileName As String
Dim fullPath As String
Const ForAppending = 8, TristateFalse = 0
Dim curDate As Date
Dim strDate As String
curDate = Date
strDate = CStr(curDate)
fileName = "DCSSInputLitigation_" & "(" & strDate & ")" & ".txt"
filePath = "C:\TempFolder\"
Set fs = CreateObject("Scripting.FileSystemObject")
fullPath = fs.BuildPath(filePath, fileName)
Set fWriter = fs.CreateTextFile(fullPath)
End Sub
When I hard code the path in the method it works but not when I use variables. Any Ideas?
Set fWriter = fs.CreateTextFile("C:\TempFolder\test.txt")
When you get the date as follows:
strDate = CStr(curDate)
you are adding / into the file name and the string value for fullPath which you create is:
C:\TempFolder\DCSSInputLitigation_(6/12/2014).txt
File names cannot have / in them on Windows so you are running into problems here.
You can either format the date or replace the / like:
strDate = replace(CStr(curDate),"/","-")
strDate = Format(curDate,"dd-mm-yyyy")
Either will work.