Exception error occurs on second call to procedure

  • Thread starter Thread starter Paul
  • Start date Start date
P

Paul

Hello,

The following code generates an exception error the *second* time it is
called.
Can anyone see what I'm doing wrong?
There is a similar example in Wrox Professional VB.NET Page 289.

Error:
An unhandled exception of type 'System.ObjectDisposedException'
occurred in mscorlib.dll
Additional information: Cannot write to a closed TextWriter.


The error occurs on this line: Debug.WriteLine("Date: " & DateTime.Now)
Code:
Dim LogFile As String = "C:\LogFile.txt"
Dim objWriter As IO.StreamWriter
objWriter = New IO.StreamWriter(LogFile, FileMode.OpenOrCreate)
Debug.Listeners.Add(New TextWriterTraceListener(objWriter))
Debug.WriteLine("Date: " & DateTime.Now)
Debug.Indent()
Debug.WriteLine("Error: " & Exception.Message)
objWriter.Flush()
objWriter.Close()
objWriter = Nothing

Thank you,
Paul
 
Try:

Dim LogFile As String = "C:\LogFile.txt"
Dim objWriter As IO.StreamWriter
objWriter = New IO.StreamWriter(LogFile, FileMode.OpenOrCreate)
Dim myTextListener As New TextWriterTraceListener(objWriter) '
<<<<----- create a var you can ref
Debug.Listeners.Add(myTextListener)
Debug.WriteLine("Date: " & DateTime.Now)
Debug.Indent()
Debug.WriteLine("Error: test")
objWriter.Flush()
objWriter.Close()
Debug.Listeners.Remove(myTextListener) ' <<<<---- remove the ref

HTH,
Greg
 
That did it.

Thanks Greg


Greg Burns said:
Try:

Dim LogFile As String = "C:\LogFile.txt"
Dim objWriter As IO.StreamWriter
objWriter = New IO.StreamWriter(LogFile, FileMode.OpenOrCreate)
Dim myTextListener As New TextWriterTraceListener(objWriter) '
<<<<----- create a var you can ref
Debug.Listeners.Add(myTextListener)
Debug.WriteLine("Date: " & DateTime.Now)
Debug.Indent()
Debug.WriteLine("Error: test")
objWriter.Flush()
objWriter.Close()
Debug.Listeners.Remove(myTextListener) ' <<<<---- remove the ref

HTH,
Greg
 
Debug.Listeners.Add(New TextWriterTraceListener(objWriter))

So this would create a temporary unamed variable by the framework, which
upon rentering the loop would create it in the same variable name/address
space correct?

At least thats what appears to be happening.

Is this by design?
 
I dunno.

Even if you assigned it to a variable it would still has a problem when you
run the procedure a second time.

I just took a look at my own code and saw it was having the same problem as
Paul's when ran twice (our code is practically verbatim from the help file
on the subject).

I added a Trace.Listeners.Remove(myTextListener) and the problem went away.

Not sure why.

So much for looking like a code guru... :^)

Greg
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top