导入.csv文件的最后一行

时间:2013-06-25 13:41:22

标签: vb.net csv

我有一个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

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

txtfile的例子

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 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

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

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

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

Dim line As String = lines(lines.Length - 1)

答案 2 :(得分: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是文件中的最后一行。

答案 3 :(得分:0)

试试这个:

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

lastLine = lines(lines.Length - 1)