Recently I worked with data temporary stored in a txt file. As the files were not present all the time at the location, the code should first check if a required file exists.
Two different ways were used based on other requirements not included here.
1. If more than one file is present, search for the most recent one (in this case, the one that was created today.)
docpath = ConfigurationManager.AppSettings("FileLocation")
filename = "testFile.txt"
filescount = System.IO.Directory.GetFiles(docpath, filename)
If filescount.Length > 0 Then
For i = 0 To filescount.Length - 1
ExistingFile = System.IO.File.GetLastWriteTime(filescount(i))
If ExistingFile.Substring(0, 10) = Today Then
'
'
End If
Next
End If
2. If a specific file exists, read the file, and add values to a newly crated list of objects.
dim docpath as String = string.empty
dim filename as String = string.Empty
docpath = ConfigurationManager.AppSettings("FileLocation")
filename = "testFile.txt"
Dim Exists As Boolean = My.Computer.FileSystem.FileExists(docpath & filename)
If Exists = True Then
Dim FileText As String = My.Computer.FileSystem.ReadAllText(docpath & filename)
Dim textLine As String()
textLine = FileText.Split(Trim(CChar(Environment.NewLine)))
If textLine.Length > 1 Then
For i = 0 To textLine.GetUpperBound(0)
If textLine(i).Trim().Length > 0 Then
frmTest.lstItems.Items.Add(textLine(i).Trim().ToUpper())
End If
Next i
End If
End If
End If
End If