2012-04-02 65 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