Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

I came across some code on this board which led me to my question. Is it necessary to close an instance of a streamwriter object if an exception arises. For example if an error occured in the below code after the sw was open and the sw is still open, should the sw be closed?

 

Private Function SaveToFile() As Boolean
       Try

           Dim bFile As String = Dir(Application.StartupPath & "\Test.txt")
           If bFile.Length > 0 Then 'Check if the file exists and delete it
               Kill(Application.StartupPath & "\Test.txt")
           End If

           'Create the file again or for the first time
           Dim sb As New FileStream(Application.StartupPath & "\Test.txt", FileMode.OpenOrCreate)
           Dim sw As New StreamWriter(sb)
           Dim nCounter As Integer

           'loop through the list and save one line at a time
           For nCounter = 0 To List1.Items.Count - 1
               sw.Write(List1.Items.Item(nCounter).ToString & vbCrLf)
           Next
           sw.Close()
           Return True
       Catch 'ignore errors
           Return False
       End Try

   End Function

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