Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

Ok,

Here my code piece..... DOnt I need to close the file here?

 

If so How?

 

          Try
               If File.Exists(frPath) Then
                   Dim rFile As StreamReader = File.OpenText(frPath)
                   ReadString = rFile.ReadToEnd()
                   stubText.Text = ReadString
               End If
               ' Q:  DO I need to close this File?  How?  Where? Here or after
               '            End Try?
           Catch
           End Try

 

vbMarkO

Visual Basic 2008 Express Edition!
Posted
Dim rFile as StreamReader
Try
   If File.Exists(frPath) Then
       rFile = File.OpenText(frPath)
       ReadString = rFile.ReadToEnd()
       stubText.Text = ReadString
   End If
Catch ex as Exception
Finally
   rFile.Close()
End Try

Posted
Dim rFile as StreamReader
Try
   If File.Exists(frPath) Then
       rFile = File.OpenText(frPath)
       ReadString = rFile.ReadToEnd()
       stubText.Text = ReadString
   End If
Catch ex as Exception
Finally
   rFile.Close()
End Try

This code will throw an NullReferenceException if the file does not exist, because no reference will ever be assigned to the rFile variable but the code will still call Close on it. You would need to test for a null reference in the Finally block:
Dim rFile as StreamReader
Try
   If File.Exists(frPath) Then
       rFile = File.OpenText(frPath)
       ReadString = rFile.ReadToEnd()
       stubText.Text = ReadString
   End If
Catch ex as Exception
Finally
   If Not rFile Is Nothing Then
       rFile.Close()
   End If
End Try

or use two Try...Catch blocks:

Dim rFile as StreamReader
Try
   If File.Exists(frPath) Then
       rFile = File.OpenText(frPath)

       Try
           ReadString = rFile.ReadToEnd()
           stubText.Text = ReadString
       Catch ex as Exception

       Finally
           rFile.Close()
       End Try
   End If
Catch ex as Exception

End Try

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...