By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,538 Members | 911 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 448,538 IT Pros & Developers. It's quick & easy.

Checking If File Exists...Best Method

P: n/a
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
Nov 21 '05 #1
Share this Question
Share on Google+
4 Replies


P: n/a
Hello,

Try:-

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

...

End If

Regards
Simon
"Peter" <pe***@mclinn.com> wrote in message
news:dc**************************@posting.google.c om...
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

Nov 21 '05 #2

P: n/a
And for countling lines is there something better?
Nov 21 '05 #3

P: n/a
* pe***@mclinn.com (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.

--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://dotnet.mvps.org/dotnet/faqs/>
Nov 21 '05 #4

P: n/a
On 13 Aug 2004 01:23:34 +0200, Herfried K. Wagner [MVP] wrote:
* pe***@mclinn.com (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.


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.
Nov 21 '05 #5

This discussion thread is closed

Replies have been disabled for this discussion.