vb.netcsvdirectoryinfo

Simple code that reads CSV values causes an error in System.IO.Directory


I can't seem to figure out why I'm getting a compilation error with this code that tries to find the most recently updated file (all CSV files) in a directory, to then pull the last line of the CSV and update a device.

The exception I get is:

Line 3 Character 10 expected end of statement.

Don't worry about the hs.SetDevice, I know that part is correct.

Imports System.IO

Sub Main()
    Dim path = System.IO.DirectoryInfo.GetFiles("C:\Users\Ian\Documents\Wifi Sensor Software").OrderByDescending(Function(f) f.LastWriteTime).First()
    Dim line = System.IO.File.ReadLines(path).Last()
    Dim fields() = line.Split(",".ToCharArray())
    Dim fileTemp = fields(2)
    hs.SetDeviceValueByRef(124, fileTemp, True)
End Sub

EDIT:
Changed Directory to DirectoryInfo


Solution

  • The worst problem is Option Strict set to Off.
    Turn it On in the Project's Properties (Project->Properties->Compile), or in the general options of Visual Studio (Tools->Options->Projects and Solutions->VB Defaults), so it's already set for new Projects.
    You can also add it on top of a file, as shown here.

    With Option Strict On, you are immediately informed when a mishap of this kind is found in your code, so you can fix it immediately.
    With Option Strict Off, some issues that come up at run-time can be very hard to identify and fix. Setting it On to try and fix the problem later is almost useless, since all the mishaps will come up all at once and you'll have a gazillion of error notifications that will hide the issue at hand.

    Option Strict On
    
    Imports System.IO
    Imports Microsoft.VisualBasic.FileIO
    
    Dim filesPath = Path.Combine(Environment.GetFolderPath(
        Environment.SpecialFolder.MyDocuments), "Wifi Sensor Software")
    Dim mostRecentFile = New DirectoryInfo(filesPath).
        GetFiles("*.csv").OrderByDescending(Function(f) f.LastWriteTime).First()
    
    Using tfp As New TextFieldParser(mostRecentFile.FullName)
        tfp.TextFieldType = FieldType.Delimited
        tfp.SetDelimiters({","})
    
        Dim fileTemp As String = String.Empty
        Try
            While Not tfp.EndOfData
                fileTemp = tfp.ReadFields()(2)
            End While
        Catch fnfEx As FileNotFoundException
            MessageBox.Show($"File not found: {fnfEx.Message}")
        Catch exIDX As IndexOutOfRangeException
            MessageBox.Show($"Invalid Data format: {exIDX.Message}")
        Catch exIO As MalformedLineException
            MessageBox.Show($"Invalid Data format at line {exIO.Message}")
        End Try
      
        If Not String.IsNullOrEmpty(fileTemp) Then
            hs.SetDeviceValueByRef(124, fileTemp, True)
        End If
    End Using