user67144
user67144

Reputation: 13

Convert this line of code from VB.NET to C#?

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)

Upvotes: 0

Views: 1602

Answers (1)

aKzenT
aKzenT

Reputation: 7915

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:

byte[] bytes = new byte[tcpClient.ReceiveBufferSize]; 

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:

byte[] bytes = new byte[tcpClient.ReceiveBufferSize];
int bytesRead = networkStream.Read(bytes, 0, tcpClient.ReceiveBufferSize);
// Output the data received from the host to the console. 
string returndata = Encoding.ASCII.GetString(bytes,0,bytesRead);

Edit: Even better to read the data in packets, so you don't need to reserve a large buffer upfront:

byte[] bytes = new byte[4096]; //buffer
int bytesRead = networkStream.Read(bytes, 0, bytes.Length);
while(bytesRead>0)
{
    // Output the data received from the host to the console. 
    string returndata = Encoding.ASCII.GetString(bytes,0,bytesRead);
    Console.Write(returndata);
    bytesRead = networkStream.Read(bytes, 0, bytes.Length);
}

Upvotes: 1

Related Questions