Using System.IO.StreamWriter

How can I determine the state of a stream writer object?  I would like to know if it is open so that I can close it in my try catch finally block.  
LVL 1
Howard BashSenior Software EngineerAsked:
Who is Participating?
 
CodeCruiserCommented:
Just add this

If IsNothing(strmwrtr) = False Then
   strmwrte.Dispose
End If


It would close itself and clear itself from memory.
0
 
Todd GerbertIT ConsultantCommented:
Use a "Using" block: http://msdn.microsoft.com/en-us/library/htd05whh(VS.80).aspx



Imports System.IO
Module Module1

    Sub Main()
        Try

            Using sw As New StreamWriter(New MemoryStream())
                For i As Integer = 0 To 10
                    sw.WriteLine("This is line " & i)
                Next
            End Using 'sw is guaranteed to be disposed here whether an exception occurs or not
        Catch ex As Exception
            Console.WriteLine("An error occurred.")
        End Try
    End Sub

End Module

Open in new window

0
 
Howard BashSenior Software EngineerAuthor Commented:
So, in a nutshell there is not status property or method and the way to "close" the stream is to dispose of it if it has been instantiated?
0
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
CodeCruiserCommented:
I have not seen any status property. Disposing it would close it as well.
0
 
Todd GerbertIT ConsultantCommented:
Yes. In the case of a finally block, as you've described, there is no need to know the status.
0
 
Todd GerbertIT ConsultantCommented:
Doh! I gotta learn to type quicker. ;)
0
 
Carlos VillegasFull Stack .NET DeveloperCommented:
If your intention is to close it then tgerbert ways is the best choice.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.