Checking If File Exists...Best Method

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
 
S

Simon Jefferies

Hello,

Try:-

If System.IO.File.Exists("filename") Then

...

End If

Regards
Simon
 
H

Herfried K. Wagner [MVP]

* (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.
 
C

Chris Dunaway

* (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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top