简体   繁体   中英

Convert C# to VB.net - byte array loop

Ok, have some sample code in C# that I need in vb.net. Usually not a big deal but my brain has completely locked up on this While loop. Overall code is doing a PUT web request with XML string and file. The While loop is reading the bytes of the the file and added to the web request (I think - again brain is locked up). As usual thanks for any help in advance.

Here is the C# while loop that I need in vb.net

while ((bytesRead = postData.Read(buffer, 0, buffer.Length)) != 0)
{
requestStream.Write(buffer, 0, bytesRead);
}

Here is what I have currently in vb.net (that is wrong)

 While (bytesRead, postData.Read(buffer, 0, buffer.Length)) <> 0
            requestStream.Write(buffer, 0, bytesRead)
        End While

The assignment inside an expression does not work in vb.net. Which actually requires more code:

bytesRead = postData.Read(buffer, 0, buffer.Length)
While bytesRead <> 0    
    requestStream.Write(buffer, 0, bytesRead)
    bytesRead = postData.Read(buffer, 0, buffer.Length)
End While

I don't believe that you can perform the assignment as expected within the While conditional statement as Visual Basic uses the = operator for both equality comparisons and assignments. This is one of the benefits of C# in that it can easily differentiate between the two (as they are different operators).

Instead, try initially reading it outside of the loop the first call and then handle it within the loop for all subsequent calls:

' Initial read '
bytesRead = postData.Read(buffer, 0, buffer.Length)
' Read if there are bytes to be read '
While bytesRead <> 0    
    ' Write the current bytes out of the buffer '
    requestStream.Write(buffer, 0, bytesRead)
    ' Read some more '
    bytesRead = postData.Read(buffer, 0, buffer.Length)
End While

C# is like other C-derived languages in allowing the use of assignment as an expression. VB does not allow this. You can either do the assignment explicitly (as done in the other answers), or you can convert it into a function.

As an example of the latter:

Function ReadBytes(<insert correct declaration for buffer here>, ByRef bytesRead as Integer) As Boolean
    bytesRead = postData.Read(buffer, 0, buffer.Length)
    Return bytesRead <> 0
End Function

While(ReadBytes(buffer, bytesRead))
    requestStream.Write(buffer, 0, bytesRead)
End While

Depending on other details that you didn't show, you might also need postData to be a parameter to ReadBytes .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM