读取 CSV 值的简单代码导致 System.IO.Directory 中的错误

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

我似乎无法弄清楚为什么我在尝试在目录中找到最近更新的文件(所有 CSV 文件)然后拉取最后一行的代码时遇到编译错误CSV 并更新设备。

我得到的异常是:

Line 3 Character 10 expected end of statement.

不用担心 hs.SetDevice,我知道那部分是正确的。

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

编辑:
将目录更改为 DirectoryInfo

  • 原来的问题是Directory.GetFiles()returns一个字符串数组,一个字符串没有LastWriteTime属性.
    这个属性属于FileInfo base class, FileSystemInfo, the object type returned by DirectoryInfo.GetFiles().
    然后,一个FileInfo对象不能传递给File.ReadLines(),这个方法需要一个字符串,所以你需要传递[FileInfo].FullName.

  • 以这种方式对路径进行硬编码并不是一件好事。使用 Environment.GetFolderPath() to get the Path of special folders, as the MyDocuments folder, and Path.Combine() 构建有效路径。

  • 最好使用TextFieldParserclass来解析CSV文件。使用起来非常简单,也足够安全。

最严重的问题是 Option Strict 设置为 Off
在项目的属性(Project->Properties->Compile)或Visual Studio(Tools->Options->Projects and Solutions->VB Defaults)的常规选项中将其设置为On,因此已为新项目设置。
您也可以将其添加到文件之上,如此处所示。

使用 Option Strict On,当在您的代码中发现此类错误时,您会立即收到通知,因此您可以立即修复它。
对于 Option Strict Off,在 运行 时出现的一些问题可能很难识别和修复。将其设置为 On 以尝试稍后解决问题几乎是无用的,因为所有的不幸事件都会同时出现,并且您将收到大量的错误通知来隐藏手头的问题。

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