How do I convert the following line of code from VB.NET to C#.
Dim bytes(tcpClient.ReceiveBufferSize) As Byte
I got the following line from the developerfusion web site, but it’s giving me wrong results in my program.
byte[] bytes = new byte[tcpClient.ReceiveBufferSize + 1];
Here is an example of my entire code in Visual Basic.
Dim tcpClient As New System.Net.Sockets.TcpClient()
TcpClient.Connect(txtIP.Text, txtPort.Text)
Dim networkStream As NetworkStream = TcpClient.GetStream()
If networkStream.CanWrite And networkStream.CanRead Then
Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes(txtSend.Text.Trim())
networkStream.Write(sendBytes, 0, sendBytes.Length)
' Read the NetworkStream into a byte buffer.
TcpClient.ReceiveBufferSize = 52428800 '50 MB
'Do I need to clean the buffer?
'Get the string back (response)
Dim bytes(tcpClient.ReceiveBufferSize) As Byte
networkStream.Read(bytes, 0, CInt(TcpClient.ReceiveBufferSize))
' Output the data received from the host to the console.
Dim returndata As String = Encoding.ASCII.GetString(bytes)
Visual Basic specifies the maximum bound of the array instead of the length of the array (arrays start at index 0), so your conversion added an extra byte. In your code however the correct way would be:
If you get wrong results, tell us what exactly is wrong. Maybe it’s another part of the code.
Edit: Remove the \0 like this:
Edit: Even better to read the data in packets, so you don’t need to reserve a large buffer upfront: