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

109 Views Asked by At

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

1

There are 1 best solutions below

1
Jimi On BEST ANSWER
  • The original problem was that Directory.GetFiles() returns an array of strings, a string doesn't have a LastWriteTime Property.
    This property belongs to the FileInfo base class, FileSystemInfo, the object type returned by DirectoryInfo.GetFiles().
    Then, a FileInfo object cannot be passed to File.ReadLines(), this method expects a string, so you need to pass [FileInfo].FullName.

  • Hard-coding a Path in that manner is not a good thing. Use Environment.GetFolderPath() to get the Path of special folders, as the MyDocuments folder, and Path.Combine() to build a valid path.

  • Better use the TextFieldParser class to parse a CSV file. It's very simple to use and safe enough.

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