Using System.IO.StreamWriter

Posted on 2011-04-22
Last Modified: 2012-05-11
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.  
Question by:hbash
    LVL 83

    Accepted Solution

    Just add this

    If IsNothing(strmwrtr) = False Then
    End If

    It would close itself and clear itself from memory.
    LVL 33

    Assisted Solution

    by:Todd Gerbert
    Use a "Using" block:

    Imports System.IO
    Module Module1
        Sub Main()
                Using sw As New StreamWriter(New MemoryStream())
                    For i As Integer = 0 To 10
                        sw.WriteLine("This is line " & i)
                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

    LVL 1

    Author Comment

    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?
    LVL 83

    Expert Comment

    I have not seen any status property. Disposing it would close it as well.
    LVL 33

    Expert Comment

    by:Todd Gerbert
    Yes. In the case of a finally block, as you've described, there is no need to know the status.
    LVL 33

    Expert Comment

    by:Todd Gerbert
    Doh! I gotta learn to type quicker. ;)
    LVL 17

    Expert Comment

    by:Carlos Villegas
    If your intention is to close it then tgerbert ways is the best choice.

    Featured Post

    Looking for New Ways to Advertise?

    Engage with tech pros in our community with native advertising, as a Vendor Expert, and more.

    Join & Write a Comment

    It’s quite interesting for me as I worked with Excel using for some time. Here are some topics which I know want to share with others whom this might help. First of all if you are working with Excel then you need to Download the Following …
    If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
    Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.
    This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor ( If you're looking for how to monitor bandwidth using netflow or packet s…

    754 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    21 Experts available now in Live!

    Get 1:1 Help Now