function to delete folders older than 10 days in vb - vb.net

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

Related

how to show todays data in datagridview

Public Sub filltable()
Dim qry As String = "select filename as FileName,filesize as FileSize,time as Time from files"
Dim ds As DataSet = New DataSet()
ds = GetQueryResult_Mysql(qry)
DataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnMode.Fill)
If (ds.Tables(0).Rows.Count > 0) Then
''For i As Integer = 0 To ds.Tables(0).Rows.Count
'' Dim fname As String = ds.Tables(0).Rows(i).Item("filename").ToString()
'' Dim fsize As String = ds.Tables(0).Rows(i).Item("filesize").ToString()
'' Dim ftime As String = ds.Tables(0).Rows(i).Item("time").ToString()
''Next
DataGridView1.DataSource = ds.Tables(0)
End If
End Sub
Assuming time is a time stamp that contains the date too
select filename as FileName,filesize as FileSize,time as Time from files WHERE time >= CURDATE()
Do please tag your database (and tag the version) next time; we shouldn't have to catch sight of a curiously named method buried in the middle of the code to know you're using MySQL

How can I calculate the next birthday programmatically

I have a data table with a date-of-birth column.
I would want to split the date apart and change the year part with today.year which is current year.
Below is my code:
Dim birthda As New SqlDataAdapter(birthcmd)
Dim birthdt As New DataTable
birthda.Fill(birthdt)
For Each rw As DataRow In birthdt.Rows
Dim dob As String = rw.Item(3)
Dim mdat As Date = FormatDateTime(dob, DateFormat.ShortDate)
Dim bday As Date = (Date.Today.Year & mdat.Month & mdat.Day)
Dim yers As Integer = DateDiff(DateInterval.Year, mdat.Date, Today.Date)
Dim moths As Integer = DateDiff(DateInterval.Month, mdat.Date, Today.Date)
Dim dys As Integer = DateDiff(DateInterval.Day, mdat.Date, Today.Date)
but I get this error:
Conversion from string "2019715" to type 'Date' is not valid.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidCastException: Conversion from string "2019715" to type 'Date' is not valid.
Source Error:
Line 149:
Line 150: Dim bday As Date = (Date.Today.Year & mdat.Month & mdat.Day)
VB.net is very peculiar when it comes to String to Date conversion.
I would recommend converting the Date from the individual components like this :
Dim bday as Date = New Date(Date.Today.Year, mdat.Month, mdat.Day)
Or as stated in the comments try using VB.Net DateTime
Dim bday as New DateTime(Date.Today.Year, mdat.Month, mdat.Day, 0, 0, 0)
thank you i think I have figured it out this is what i did. I calculated for the age with respect to current year and added the result to the year part of the date of birth.
here is the code
For Each rw As DataRow In birthdt.Rows
Dim dob As DateTime = rw.Item(2)
Dim mdat As Date = FormatDateTime(dob, DateFormat.ShortDate)
Dim yers As Integer = DateDiff(DateInterval.Year, mdat.Date, Today.Date)
Dim moths As Integer = DateDiff(DateInterval.Month, mdat.Date, Today.Date)
Dim dys As Integer = DateDiff(DateInterval.Day, mdat.Date, Today.Date)
Dim ndob As Date = (DateAdd(DateInterval.Year, yers, mdat))
Dim yers2 As Integer = DateDiff(DateInterval.Year, ndob.Date, Today.Date)
Dim moths2 As Integer = DateDiff(DateInterval.Month, ndob.Date, Today.Date)
Dim dys2 As Integer = DateDiff(DateInterval.Day, ndob.Date, Today.Date)
I am basing this on what you wrote in a comment:
want to check those who have upcoming birthdays for a particular week.
It is fiddly to deal with leap years and dates which might be in the next year, but I think I've got all the cases covered here.
I made a table "Pets" in SQL Server with columns "Name" and "DOB", and put some data in.
I made a new Windows Forms project and added a multi-line textbox to Form1, and used this code:
Imports System.Data.SqlClient
Imports System.Text
Public Class Form1
Sub ShowUpcomingBirthdays()
Dim csb As New SqlConnectionStringBuilder With {.DataSource = ".\SQLEXPRESS", .InitialCatalog = "Testing", .IntegratedSecurity = True}
Dim birthdt As New DataTable()
Dim sql = "SELECT [Name], [DOB] FROM [Pets]"
Using conn As New SqlConnection(csb.ConnectionString)
Using sqlCmd As New SqlCommand(sql, conn)
Dim da As New SqlDataAdapter With {.SelectCommand = sqlCmd}
da.Fill(birthdt)
End Using
End Using
Dim matchEarliest = DateTime.Today
Dim matchLatest = matchEarliest.AddDays(8)
Dim sb As New StringBuilder ' somewhere to save the matching data
For Each r As DataRow In birthdt.Rows
Dim dob = Convert.ToDateTime(r.Item("DOB"))
' Allow for leap years by transferring the birthday to 1st March - some countries would use 28th February.
If DateTime.IsLeapYear(dob.Year) AndAlso Not DateTime.IsLeapYear(matchEarliest.Year) AndAlso dob.Month = 2 AndAlso dob.Day = 29 Then
dob = dob.AddDays(1)
End If
Dim nextBirthday = New DateTime(matchEarliest.Year, dob.Month, dob.Day)
If dob.Month <= matchEarliest.Month AndAlso dob.Day < matchEarliest.Day Then
' birthday has already happened this calendar year, make it next year
nextBirthday = nextBirthday.AddYears(1)
End If
If nextBirthday >= matchEarliest AndAlso nextBirthday < matchLatest Then
' the record is in the required range
sb.AppendLine(CStr(r.Item("Name")) & " " & dob.ToString("ddd dd MMMM"))
End If
Next
TextBox1.Text = sb.ToString()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ShowUpcomingBirthdays()
End Sub
End Class
It includes birthdays which happen "today" (you might not want to miss that), but you could
Dim matchEarliest = DateTime.Today.AddDays(1)
Dim matchLatest = matchEarliest.AddDays(7)
if you didn't want to include today.
I made a little class called Employee (it is at the bottom of the code). This answer is a bit similar to #AndrewMorton. I broke up the Sub into several functions that can be altered to suit without breaking the rest.
Private Sub DisplayUpcomingBirthdays()
Dim lstBirthdays As New List(Of Employee)
Dim dt = RetrieveBirthdays()
For Each rw As DataRow In dt.Rows
Dim CurrentYearBirthday As Date = GetCurrentYearBD(CDate(rw.Item("Birthdate")))
If IsBDThisWeek(CurrentYearBirthday) Then
lstBirthdays.Add(New Employee(CurrentYearBirthday, rw.Item("Name").ToString))
End If
Next
Dim SortedList = SortByBirthdays(lstBirthdays)
ListBox1.DataSource = SortedList
End Sub
Private Function RetrieveBirthdays() As DataTable
Dim query = "Select Name, Birthdate From Employes;"
Dim birthdt As New DataTable
Using cn As New SqlConnection("YourConnectionString")
Using cmd As New SqlCommand(query, cn)
cn.Open()
birthdt.Load(cmd.ExecuteReader)
End Using
End Using
Return birthdt
End Function
Private Function GetCurrentYearBD(BirthDate As Date) As Date
Dim Day As Integer = BirthDate.Day
Dim Month As Integer = BirthDate.Month
Dim Year As Integer = Now.Year
'Bithday is celebrated on the 28th when it is not a leap year
If Month = 2 AndAlso Day = 29 AndAlso Not DateTime.IsLeapYear(Year) Then
Day = 28
End If
Return New DateTime(Year, Month, Day)
End Function
Private Function IsBDThisWeek(BD As Date) As Boolean
Dim Tomorow = Now.AddDays(1)
Dim WeekFromNow = Now.AddDays(7)
If BD >= Tomorow AndAlso BD <= WeekFromNow Then
Return True
End If
Return False
End Function
Private Function SortByBirthdays(Employees As List(Of Employee)) As List(Of Employee)
Dim lst = (From emp In Employees
Order By emp.Birthdate
Select emp).ToList
Return lst
End Function
Public Class Employee
Public Property Birthdate As Date
Public Property Name As String
Public Sub New(BD As Date, eName As String)
Birthdate = BD
Name = eName
End Sub
Public Overrides Function ToString() As String
Return $"{Name}, {Birthdate.ToString("MMMM dd")}"
End Function
End Class

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).

How can I improve the efficiency of my simple file-splitting program

I have a simple program that reads a .txt file, and then splits it up into many files of "pMaxRows" number of rows. These .txt files are huge - some are nearly 25Gb. Right now it is not running fast enough for my liking, I feel that there should be a way to improve the efficiency by maybe reading/writing multiple lines at once, but I am not very experienced with vb.net streamreader/streamwriter.
Code is below:
Public Sub Execute(ByVal pFileLocation As String, _
ByVal pMaxRows As Int32)
Dim sr As IO.StreamReader
Dim Row As String
Dim SourceRowCount As Int64
Dim TargetRowCount As int64
Dim TargetFileNumber As Int32
''Does the file exist in that location?
If IO.File.Exists(pFileLocation) = False Then
Throw New Exception("File does not exist at " & pFileLocation)
End If
''Split FileLocation into FileName and Folder Location
Dim arrFileLoc() As String = pFileLocation.Split("\")
Dim i As Integer = arrFileLoc.Length - 1
Dim FileName As String = arrFileLoc(i)
Dim FileLocationLength As Integer = pFileLocation.Length
Dim FileNameLength As Integer = FileName.Length
Dim Folder As String = pFileLocation.Remove(FileLocationLength - FileNameLength, FileNameLength)
''Read the file
sr = New IO.StreamReader(pFileLocation)
SourceRowCount = 0
TargetRowCount = 0
TargetFileNumber = 1
''Create First Target File Name
Dim TargetFileName As String
TargetFileName = TargetFileNumber & "_" & FileName
''Open streamreader and start reading lines
Do While Not sr.EndOfStream
''if it hits the target number of rows:
If (TargetRowCount = pMaxRows) Then
''Advance target file number
TargetFileNumber += 1
''Create New file with target file number
TargetFileName = TargetFileNumber & "_" & FileName
''Set target row count back to 0
TargetRowCount = 0
End If
''Read line
Row = sr.ReadLine()
''Write line
Using sw As New StreamWriter(Folder & TargetFileName, True)
sw.WriteLine(Row)
End Using
SourceRowCount += 1
TargetRowCount += 1
Loop
End Sub
Anyone have any suggestions? Even directing me to the right place if this has been answered before would be much appreciated

Open all files within Start Date & End Date.

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