system.NullReferenceError

  • Thread starter Thread starter Leo
  • Start date Start date
L

Leo

In my vb.net project, I created a module1.
and in module1, I declared the "sw" as a new streamwriter.

Public sw As StreamWriter = New StreamWriter("OutPut.txt")

In Form1.vb, I got an error with the following code.
sw.writeLine(datetime.now)
(I tracked the code and in the watch window, I found "sw"
is nothing.)

Can somebody tell me why ?
 
I have used the follwoing (similar scenario) code in my program which works
without any problem:

dim fst as new filestream("C:\myfile.txt", Filemode.create)
dim sr as streamwriter
sr = new streamwriter(fst)
sr.writeline(1)
sr.writeline(2)
 
It sounds like you didn't declare it in a Public Function..
Hope this helps..
Ronald Walker
 
It didn't work in my machine.
I tried the following.
In module1:
Public fst as new
filestream "C:\myfile.txt",Filemode.create)
Public sr as streamwriter
sr = new streamwriter(fst)


And in my startup form:
sr.writeline(1)
sr.writeline(2)

It's weird. :(
 
StreamWriter is a reference type and you declared it with
= New Streamwriter. Reference type assignments only
assign a pointer, and the object New Streamwriter is
pointing to can be destroyed because THAT particular
StreamWriter is no longer in use. Declare it like this
Public sw As New StreamWriter("OutPut.txt")
That makes the object stay in memory as long as sw is in
existance, not as long as New StreamWriter is in existance.
 
Found it.. it's staying in the buffer.. after you write the line add:

sw.Flush()

now should work...
Regards,
Ronald Walker
 
StreamWriter is a reference type and you declared it with
= New Streamwriter. Reference type assignments only
assign a pointer, and the object New Streamwriter is
pointing to can be destroyed because THAT particular
StreamWriter is no longer in use.

[Leo](what happens if the streamwriter is declared with
New in module level? Will it be destroyed ? )

Declare it like this Public sw As New StreamWriter
("OutPut.txt") That makes the object stay in memory as
long as sw is in existance, not as long as New
StreamWriter is in existance.
[Leo] Can you explain in more details?


Thanks
Leo
 
Back
Top