Home > front end >  While conversion from C# not working the same in VB.NET
While conversion from C# not working the same in VB.NET

Time:01-13

I'm probably being dumb here. I'm doing a conversion from C# to VB.NET for a little piece of code that downloads videos but though this works fine in C#, it doesn't in VB.NET. The code is this:

using (var input = await client.GetStreamAsync(video.Uri))
        {
            byte[] buffer = new byte[16 * 1024];
            int read;
            int totalRead = 0;
            Console.WriteLine("Download Started");
            while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
            {
                output.Write(buffer, 0, read);
                totalRead  = read;
                Console.Write($"\rDownloading {totalRead}/{totalByte} ...");
            }
            Console.WriteLine("Download Complete");
        }

In C#, this downloads a video fine but in VB.NET, the 'while' line syntax doesn't convert properly and therefore nothing downloads. Can anyone help with the VB.NET syntax for the 'while' line please? It seems otherwise that 'read' never becomes more than zero.

The VB.NET code currently looks like this:

Using input = Await client.GetStreamAsync(video.Uri)
            Dim buffer = New Byte(16 * 1024) {} '(81919) {} ' (16 * 1024) {}
            Dim read As Integer
            Dim totalRead = 0
            Console.Write("Download Started")
            While read = (input.Read(buffer, 0, buffer.Length) > 0)
                output.Write(buffer, 0, read)
                totalRead  = read
                Console.Write($"Downloading {totalRead}/{totalByte} ...")
            End While
            Console.Write("Download Complete")
        End Using

CodePudding user response:

VB uses the same operator for both assignment and equality testing, so you any attempted assignment within an expression will be interpreted as an equality test. The solution is to extract the assignment and reproduce it just before the loop and at the end of the loop:

read = input.Read(buffer, 0, buffer.Length)
Do While read > 0
    output.Write(buffer, 0, read)
    totalRead  = read
    Console.Write($"Downloading {totalRead}/{totalByte} ...")
    read = input.Read(buffer, 0, buffer.Length)
Loop

VB could be enhanced to have a separate operator to allow assignments within expressions (see the Python 'walrus' operator), but there are no planned changes to the language any longer.

  • Related