File Access in VB.Net

Listed below is an example of file access in VB.Net, utilizing many of the I/O functions. First the routine creates a file, then deletes it. This routine is used only for demonstration purposes.


Sub FilePurge()

Static dtLastPurgeTime As DateTime
Dim dtNow As DateTime
Dim intCounter As Integer
Dim Files() As String
Dim strGUID As String, strTXTName As String

While True
strGUID = System.Guid.NewGuid.ToString
strTXTName = "C:\Temp\STB_" & strGUID & ".TXT"

'Create a uniquely named .TXT file
Dim swTXT As StreamWriter
swTXT = File.AppendText(strTXTName)
swTXT.WriteLine(strGUID)
swTXT.Close()

'Wait 2 seconds before proceeding
System.Threading.Thread.Sleep(2000)

dtNow = Now
Dim lTimeDiff As Long = DateDiff(DateInterval.Hour, dtLastPurgeTime, dtNow)

If lTimeDiff > 24 And Now.Hour = 22 Then 'Check if last purge was more then 24 hours ago and current hour is 10PM

'Purge *.TXT files
Files = Directory.GetFiles("C:\Temp", "STB_*.TXT")
For intCounter = Files.GetLowerBound(0) To Files.GetUpperBound(0)
If DateDiff(DateInterval.Minute, File.GetCreationTime(Files(intCounter)), dtNow) > 30 Then 'Purge only if file is older than 30 minutes
File.Delete(Files(intCounter))
End If
Next intCounter

'Update Purge Time
dtLastPurgeTime = Now()

End If

End While

Error_Handler:
Resume Next 'If an error occured while deleting a file, skip it this iteration and move to the next file

End Sub

Comments

Popular posts from this blog

Working with double quotes (") in VB.Net

FoxCon 2019

Sep '19 Announcements