2011-07-26 33 views
2

如何計算no。我們上傳的文件中的行可能是文本文件或csv或excel文件。 即時通訊使用的代碼來獲取記錄計數是這樣的:使用vb.net讀取的行數

Dim FileCount = From lin1 As String In File.ReadAllLines(hidFilePath.Value.ToString()) 
Let dd = lin1.Count 
Select dd 
Dim file_count As Integer = FileCount.Count 

,但在某些情況下,即時得到錯誤計數。它沒有顯示確切的數字。

請幫助,我應該能夠得到沒有循環每個記錄在文件中的計數。

謝謝。

+0

@chinnu:閱讀本http://stackoverflow.com/faq#howtoask –

回答

6

ReadAllLines返回一個字符串數組,因此您可以簡單地獲取數組的長度。

Dim file_count As Integer = _ 
    File.ReadAllLines(hidFilePath.Value.ToString()).Length 
+1

如果它不工作出於某種原因,ReadAllLines有一個重載,您可以發送不同的編碼,這可能有助於在某些情況下:IO.ReadAllLines(路徑,編碼) – Stefan

1

編輯:閱讀問題快,用循環解決方案

你可以設置你linecount爲整數,並具有讀取到文件末尾的讀者回答。

Dim sr As New StreamReader("file path here")  
Dim lineCount As Integer = System.Text.RegularExpressions.Regex.Split(sr.ReadToEnd(), Environment.NewLine).Length 
sr.Close() 

您可以使用一個計數變量並遍歷文件,直到theres沒什麼

 ''name count and set it to 0 
     Dim count As Integer 
     count = 0 
     Dim obj As StreamReader 
     obj = New StreamReader("C:\...\source.txt") 
     ''loop through the file until the end 
     Do Until obj.ReadLine Is Nothing 
      count = count + 1 
     Loop 
     ''close file and show count 
     obj.Close() 
     MessageBox.Show(count) 
+0

OP特別要求解決方案不需要遍歷整個文件。 –

+0

Ahhhh哈哈沒有看到這一行。我跳過槍,病假留給參考其他誰可能在這裏絆倒。 – sealz

+0

此RealAllLines方法適用於獲取所有文本文件的計數。但我想獲得的行數Excel文件太...是的,我需要沒有循環通過.. – chinnu