0

I struggled with the following piece of code:

    Dim req = WebRequest.Create(Uri)
    Dim resp = req.GetResponse()
    Dim stream As Stream = resp.GetResponseStream()

    Dim Buffer As Byte() = New Byte(1023) {}
    Dim MemStream As New MemoryStream()
    Dim BytesRead As Integer = 0
    Dim totalBytesRead As Long = 0

    Dim reader As New BinaryReader(stream)

    While ((BytesRead = reader.Read(Buffer, 0, Buffer.Length)) > 0)
        BytesRead = reader.Read(Buffer, 0, Buffer.Length)
        MemStream.Write(Buffer, 0, BytesRead)
        totalBytesRead += BytesRead
    End While

The while loop was never entered, despite data was available in the reader. The variable BytesRead was never set, making me think that it would treat the "BytesRead = reader.Read(...)" as an equality validater. However with no luck, as i in debug mode attempted to change the BytesRead variable to 1024 (the length of the buffer (max read value)) but with the same negative outcome.

I solved the issue, changing the while loop to the following "do-while" loop:

    Do
        BytesRead = reader.Read(Buffer, 0, Buffer.Length)
        MemStream.Write(Buffer, 0, BytesRead)
        totalBytesRead += BytesRead
    Loop While BytesRead > 0

My question goes; why is the while loop not working as i intend?:

((BytesRead = reader.Read(Buffer, 0, Buffer.Length)) > 0) => ((output) > 0)

1 Answer 1

2

Put Option Strict On and you will see what is happening. In VB, the = operator is both a assignment operator and a comparison. When used in a while it will compare both value and return true or false. Then it'll try to do a > 0 on a Boolean value (which isn't value).

In short

While ((BytesRead = reader.Read(Buffer, 0, Buffer.Length)) > 0)

Will do: Is BytesRead equal to reader.Read(Buffer, 0, Buffer.Length) ? Is this Boolean value greater than 0.

I think this code would work un C# since it has = and ==.

Sign up to request clarification or add additional context in comments.

6 Comments

I will just give it a go.
@MortenKristensen I suggest you go and set Option Strict On right away for the whole project :)
Yes, I have done that for all my latest projects, however this project I'm currently working within is fairly old and the option has never been enabled making it very difficult to enable unfortunately.
But very nice answer, that is what i expected was happening, however, can you explain the following; i attempted to change the value manually while debugging: BytesRead = 1024. How is this: while((1024 = 1024) > 0) not entering the loop, as it essentially becomes while([true==1] > 0)?
@MortenKristensen check out one of my question as to why True = -1
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.