2013-06-25 5 views
0

저는 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 
+0

한 번에 .csv 파일을 메모리에 읽을 수있을만큼 작습니까? 아니면 거대한 파일입니까? –

+0

이 파일은 30 줄 정도의 작은 파일입니다. – yolad

+0

C#에서는 [this] (http://stackoverflow.com/questions/11625595/read-last-line-of-text-file)가 찾고있는 내용에 대한 답변을 제공합니다. – shahkalpesh

답변

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 
+0

간단히 고맙다! – yolad

+0

[대답을 올바른 것으로 표시] (http://meta.stackexchange.com/a/5235/208536)를 고려하고 대답이 도움이된다면 – SysDragon

0

예는 다음을보십시오 : 당신은 단 한 줄 읽고

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

lastLine = lines(lines.Length - 1) 
1

. 대신과 같이, ReadToEnd을 (사용) 한 다음 새 라인으로 분할 : 편집의 부부와 함께

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

당신은 당신이 원하는 것을 얻을 수 있습니다

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

그런 다음 마지막 행으로 이동할 수 있습니다 기존 코드 :

시프트

While line IsNot Nothing 

     line = reader.ReadLine() 
    End While 

으로 직후

Dim line As String = reader.ReadLine() 

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

지금 line2이 파일의 마지막 라인, 다른

Dim line2 As String = Nothing 

을 추가하고 While 루프에

 line2 = line 

삽입합니다.

+1

그는 모든 필드를 읽은 후 while 루프는 첫 번째 줄에서 데이터를 가져 오는 이유입니다. –

+0

@smoore 그래서 내 첫 번째 라인은 'While' 루프를 첫 번째'Dim '바로 다음으로 옮기는 것입니다. –

+0

실제로 그렇습니다! 미안 나는 그 권리를 따라 가지 않았다. +1 선생님! –