1

I've been getting all turned around regarding this section of code. The NullReferenceException only occurs at runtime.

Public Sub SendData(ByVal b As String)
    Dim data(2048) As Byte
    data = System.Text.Encoding.ASCII.GetBytes(b)
    stream.Write(data, 0, data.Length)
End Sub

The intent is take a string, and stream the bytes of the string over to another computer. The stream.Write portion of the code is what's throwing the NullReferenceException part. However, I checked through debugging that the data portion does get the bytes from the Encoding portion of the code. So I'm not sure why it's throwing the NullReferenceException.

John Saunders
  • 157,405
  • 24
  • 229
  • 388
Gith
  • 47
  • 6

2 Answers2

1

You need to declare a New NetworkStream. Plus, dim your byte array like this:

 Dim myBuffer() As Byte = Encoding.ASCII.GetBytes(b)
 myNetworkStream.Write(myBuffer, 0, myBuffer.Length) 
OneFineDay
  • 8,789
  • 3
  • 22
  • 34
0

My guess is that you haven't initialized your stream object with new keyword. Look at here

Also a couple of things:

1) Do not initialize your byte array yourself. Let this task done by the `GetBytes` to return an initialized array and just store it in a variable.

2) Before writing to stream always check if you get something in your stream or not. 

Something like: (untested)

Public Sub SendData(ByVal b As String)
    If (b IsNot Nothing AndAlso Not String.IsNullOrEmpty(b)) Then
       Dim data() As Byte = System.Text.Encoding.ASCII.GetBytes(b) ' or use List<Byte> instead.
       If( data IsNot Nothing AndAlso data.Length > 0) Then stream.Write(data, 0, data.Length)
    Else
       ' Incoming data is empty
    End If

    ' Don't forget to close stream
End Sub

Hope it helps!

NeverHopeless
  • 10,503
  • 4
  • 33
  • 53
  • Thank you! This was indeed very helpful. – Gith Jun 10 '13 at 19:30
  • @DonA, Buddy i have mentioned others things too, which you haven't mentioned. My guess was not related to your answer instead the comment posted by OP at the top of question. In many SO question people have same answers with slightly different things. So be positive and polite. – NeverHopeless Jun 10 '13 at 20:34