我似乎不明白为什么我会在这段代码中得到一个编译错误,该代码试图在目录中找到最近更新的文件(所有CSV文件),然后拉出CSV的最后一行并更新设备。
我得到的例外是:
第3行字符10预期语句的结尾。
别担心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
发布于 2021-03-13 23:17:39
LastWriteTime属性。
此属性属于FileInfo基类FileSystemInfo,它是DirectoryInfo.GetFiles()返回的对象类型。
然后,FileInfo对象不能传递给File.ReadLines(),该方法需要一个字符串,因此需要传递[FileInfo].FullName。最糟糕的问题是选项严格设置为Off。
在项目的属性( On )或Visual的一般选项(Tools->Options->Projects and Solutions->VB Defaults)中将其转换为Project->Properties->Compile,因此它已经为新项目设置好了。
您还可以将其添加到文件的顶部,如下所示。
使用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 Usinghttps://stackoverflow.com/questions/66618795
复制相似问题