我似乎无法弄清楚为什么我会收到此代码的编译错误,该代码试图在目录中查找最近更新的文件(所有 CSV 文件),然后拉取 CSV 的最后一行并更新设备。
我得到的例外是:
第 3 行 字符 10 预期语句结尾。
不用担心hs.SetDevice
,我知道那部分是正确的。
Imports System.IO
Sub Main()
Dim path = System.IO.DirectoryInfo.GetFiles("C:UsersIanDocumentsWifi 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() 返回一个字符串数组,一个字符串没有
LastWriteTime
属性.
此属性属于 FileInfo 基类 FileSystemInfo,该对象类型由 DirectoryInfo.GetFiles().
返回,那么一个FileInfo
对象不能传递给File.ReadLines()
,这个方法需要一个字符串,所以需要传递[FileInfo].FullName
。 -
以这种方式对路径进行硬编码并不是一件好事。使用 Environment.GetFolderPath() 获取特殊文件夹的路径(作为 MyDocuments 文件夹),使用 Path.Combine() 构建有效路径。
-
最好使用 TextFieldParser 类来分析 CSV 文件。它使用起来非常简单,而且足够安全。
最糟糕的问题是选项严格设置为Off
.
将其On
在项目的属性(Project->Properties->Compile
)或Visual Studio的常规选项(Tools->Options->Projects and Solutions->VB Defaults
)中,因此它已经设置为新项目.
您也可以将其添加到文件顶部,如下所示。
使用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