【问题标题】:Simple code that reads CSV values causes an error in System.IO.Directory读取 CSV 值的简单代码会导致 System.IO.Directory 中出现错误
【发布时间】:2021-03-13 21:41:16
【问题描述】:

我似乎无法弄清楚为什么我在尝试在目录中查找最近更新的文件(所有 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

【问题讨论】:

  • 小心基于,的拆分,如果一个 cel 包含此字符,则一切都以错误的方式完成。

标签: vb.net csv directoryinfo


【解决方案1】:
  • 原来的问题是Directory.GetFiles()返回一个字符串数组,一个字符串没有LastWriteTime属性。
    该属性属于FileInfo基类FileSystemInfoDirectoryInfo.GetFiles()返回的对象类型。
    那么FileInfo对象不能传递给File.ReadLines(),这个方法需要一个字符串,所以需要传递[FileInfo].FullName

  • 以这种方式硬编码路径不是一件好事。使用Environment.GetFolderPath()获取特殊文件夹的路径,作为MyDocuments文件夹,Path.Combine()构建有效路径。

  • 最好使用TextFieldParser 类来解析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

【讨论】:

  • 非常感谢。我让它工作了。这是我的错。我的环境设置不正确,我犯了初学者 .net 错误。感谢您给我一些分析和工作以增强我的 .net 技能的东西。
猜你喜欢
  • 2018-10-30
  • 2014-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-11
  • 2013-03-27
  • 2018-04-30
相关资源
最近更新 更多