【问题标题】:NullReferenceException (System.Text.Encoding.ASCII.GetBytes) [duplicate]NullReferenceException(System.Text.Encoding.ASCII.GetBytes)[重复]
【发布时间】:2013-06-10 04:48:50
【问题描述】:

关于这部分代码,我已经完全搞定了。 NullReferenceException 仅在运行时发生。

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

目的是获取一个字符串,并将该字符串的字节流式传输到另一台计算机。代码的 stream.Write 部分是抛出 NullReferenceException 部分的原因。但是,我通过调试检查了数据部分确实从代码的编码部分获取字节。所以我不确定它为什么会抛出 NullReferenceException。

【问题讨论】:

  • 流在Dim stream As NetworkStream 声明。不确定这是否正确。

标签: .net vb.net nullreferenceexception


【解决方案1】:

您需要声明一个新的NetworkStream。另外,像这样调暗你的字节数组:

 Dim myBuffer() As Byte = Encoding.ASCII.GetBytes(b)
 myNetworkStream.Write(myBuffer, 0, myBuffer.Length) 

【讨论】:

  • 非常感谢!您的答案和其他答案都非常有帮助
【解决方案2】:

我的猜测是 you haven't initialized 你的 stream 对象带有 new 关键字。看here

还有几件事:

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. 

类似:(未经测试

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

希望对你有帮助!

【讨论】:

  • 谢谢!这确实很有帮助。
  • @DonA,伙计,我也提到了其他事情,你没有提到。我的猜测与您的答案无关,而是 OP 在问题顶部发布的评论。在许多 SO 问题中,人们的答案相同,但事物略有不同。所以要积极有礼貌。
猜你喜欢
  • 1970-01-01
  • 2020-07-13
  • 2019-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-17
  • 1970-01-01
相关资源
最近更新 更多