2012-04-02 70 views
0

如何将以下代码行从VB.NET转换为C#。将这行代码从VB.NET转换为C#?

Dim bytes(tcpClient.ReceiveBufferSize) As Byte 

我从developerfusion网站下了一行,但它在我的程序中给了我错误的结果。

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

这是我在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) 
+0

谷歌当然! http://converter.telerik.com/ – 2012-04-02 14:04:22

+1

为什么你在缓冲区大小声明中加1? – Oded 2012-04-02 14:04:42

+0

该代码错误。我该如何翻译此代码昏暗的字节(tcpClient.ReceiveBufferSize)作为字节 – user67144 2012-04-02 14:06:55

回答

1

Visual Basic中指定绑定的阵列,而不是阵列(阵列索引0处开始)的长度的最大值,所以转换增加了一个额外的字节。然而,在您的代码中,正确的方法是:

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

如果您得到错误的结果,请告诉我们究竟发生了什么错误。也许这是代码的另一部分。

编辑:删除\ 0这样的:

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); 

编辑:更妙的是读取数据包中的数据,所以你不需要保留一个大的缓冲前期:

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); 
} 
+0

在返回数据中,我得到了很多0 \ 0 \字符。似乎vb能够删除所有的数据,当我从套接字获取数据时,但是当我运行C#代码时,我得到一堆\ 0字符。怎么可以在处理呢? \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 networkStream.Read会返回您读取的字节数,您可以将它传递给Encoding.ASCII.GetString作为参数。\ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ – user67144 2012-04-02 14:20:00

+0

,所以你只能转换实际读取的字节。此外,您应该可以使用修剪命令删除剩余的\ 0字符。 – aKzenT 2012-04-02 14:26:09

+0

你有没有机会举例说明如何计算字节数,然后将值传递给编码 – user67144 2012-04-02 14:54:33