Checking FileExists b4 StreamReader.

Jay1b

Well-known member
Joined
Aug 3, 2003
Messages
640
Location
Kent, Uk.
I am using streamreader to read from a file upon startup, but if this file doesnt exist, or is empty the program crashes at startup.

This file is a log file, and is created by the program at a later point.

I could solve the problem by putting the declaration for the streamreader in an if statement which checks if file exists, but i am old fashioned, and this just seems wrong.

So what i am basically asking it is whether i can stop it from crashing if the file doesnt exist. Heres is the declaration line

Code:
Dim sr As New StreamReader(LogPath & ".hist")

Thanks.
 
Code:
Dim sr as streamreader
try
    sr = New StreamReader(LogPath & ".hist")
catch 
    handle error
end try
would handle the error but why not just carry on checking first, not sure why making sure something can be done before doing it is old fashioned.
 
Thank you!

I have always just put ALL declarations at the top of the coding, as has all my colleagues, i can be quite flexable to make life easier, but it would make it alot harder for my colleagues to understand, if i was ill. Considering most of them last used VB back in the days of version 3. :)
 
how about declaring it it at the top and checking later on when you open the file
Code:
dim sr as streamreader
do other stuff here

if file.exists(LogPath & ".hist") then
    sr = new streamreader(LogPath & ".hist")
else
    error handled here
end if
 
Yeah thats what i done after i saw your first post.

Thanks for you help again. I am glad they made you a Forum Leader as you always seem to be the person who solves my idiotic problems, you might as well get some recognisition for it :)
 
Back
Top