Checking If File Exists...Best Method

  • Thread starter Thread starter Peter
  • Start date Start date
P

Peter

Currently I'm using the method below, is there someting more efficient?:

Imports System.IO
Public Class CountLine
Public Shared Function CountLines(ByVal FileName As String) As Integer
Dim fs As IO.FileStream
Dim sr As IO.StreamReader
Dim Result As Integer
Try
fs = New IO.FileStream( _
FileName, IO.FileMode.Open, _
IO.FileAccess.Read, IO.FileShare.Read _
)

sr = New IO.StreamReader(fs)

Do
If sr.ReadLine Is Nothing Then Exit Do

Result += 1
Loop

Return (Result)
Catch
Result = 0
End Try

End Function



End Class
 
* (e-mail address removed) (Peter) scripsit:
And for countling lines is there something better?

Looping through the lines until the end of the file is reached and
counting the lines read from the files is the best approach.
 
* (e-mail address removed) (Peter) scripsit:

Looping through the lines until the end of the file is reached and
counting the lines read from the files is the best approach.

That depends on the structure of the file. If all the lines are the same
length, then you can take the filesize and divide by the line length.

But if the lines in the file are variable length, the what Herfried
suggested is probably the best way.


--
Chris

dunawayc[AT]sbcglobal_lunchmeat_[DOT]net

To send me an E-mail, remove the "[", "]", underscores ,lunchmeat, and
replace certain words in my E-Mail address.
 
Back
Top