0

我有一个 csv 文件,我只需要将最后一行放入单独的文本框中。

Imports System.IO

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    End Sub

    Private Sub btnConditions_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConditions.Click
        Using reader As New StreamReader("C:\temp\Apr12log.txt")
            Dim line As String = reader.ReadLine()


            Dim fields() As String = line.Split(",".ToCharArray())
            Dim fileDate = CDate(fields(0))
            Dim fileTime = fields(1)
            Dim fileTemp = fields(2)
            Dim fileHum = fields(3)
            Dim fileWindSpeed = fields(4)
            Dim fileWindGust = fields(5)
            Dim fileWindBearing = fields(6)

            While line IsNot Nothing

                line = reader.ReadLine()
            End While
            txtDate.Text = CStr(fileDate)
        End Using

    End Sub

End Class

它只输入第一行我不知道如何只得到最后一行。

txt 文件示例

01/04/12,00:00,5.4,80,3.0,4.5,9.6,261,0.0,0.0,1025.0,1.0,16.8,43,4.0,3.8,5.4,0.0,0,0.0
4

4 回答 4

3

或者,您可以使用 System.IO.File ReadLines()函数,它为您提供一个可以调用 Last() 的枚举。

Private Sub btnConditions_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConditions.Click

        Dim line As String = System.IO.File.ReadLines("C:\temp\Apr12log.txt").Last()

        Dim fields() As String = line.Split(",".ToCharArray())
        Dim fileDate = CDate(fields(0))
        Dim fileTime = fields(1)
        Dim fileTemp = fields(2)
        Dim fileHum = fields(3)
        Dim fileWindSpeed = fields(4)
        Dim fileWindGust = fields(5)
        Dim fileWindBearing = fields(6)

        txtDate.Text = CStr(fileDate)

End Sub
于 2013-06-25T14:16:35.290 回答
1

你只阅读一行。而是使用 ReadToEnd() 然后用新行拆分,如下所示:

Dim lines() As String = reader.ReadToEnd().Split(Environment.NewLine)

然后你可以移动到最后一行:

Dim line As String = lines(lines.Length - 1)
于 2013-06-25T13:46:32.470 回答
1

您可以通过对现有代码进行一些编辑来获得所需的内容:

转移

   While line IsNot Nothing

        line = reader.ReadLine()
   End While

就在之后

   Dim line As String = reader.ReadLine()

加上另一个

   Dim line2 As String = Nothing

并插入

       line2 = line

进入While循环,即

   While line IsNot Nothing
        line2 = line
        line = reader.ReadLine()
   End While

现在line2是文件中的最后一行。

于 2013-06-25T13:52:05.353 回答
0

尝试这个:

Dim lines() As String = File.ReadAllLines("C:\temp\Apr12log.txt")

lastLine = lines(lines.Length - 1)
于 2013-06-25T13:45:39.727 回答