You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#转VB.NET时While循环语法错误导致视频下载失败求助

VB.NET 正确实现视频下载的循环写法

问题原因

你当前的VB.NET代码中,While循环的条件写法完全错误:
While read = (input.Read(buffer, 0, buffer.Length) > 0)
这里是把input.Read(...) > 0的布尔结果(True对应-1,False对应0)赋值给read,导致read永远不会是正整数,循环无法正常执行。

另外,VB.NET中New Byte(16 * 1024) {}创建的是长度为16*1024 +1的数组,和C#里new byte[16*1024](长度16384)的缓冲区不一致,需要修正数组定义。

正确的VB.NET代码

Using input = Await client.GetStreamAsync(video.Uri)
    ' 定义和C#长度一致的16KB缓冲区
    Dim buffer = New Byte((16 * 1024) - 1) {}
    Dim read As Integer
    Dim totalRead = 0
    Console.WriteLine("Download Started")
    
    ' 先执行一次读取,再进入循环判断
    read = input.Read(buffer, 0, buffer.Length)
    While read > 0
        output.Write(buffer, 0, read)
        totalRead += read
        Console.Write($"\rDownloading {totalRead}/{totalByte} ...")
        ' 循环内再次读取,更新read的值
        read = input.Read(buffer, 0, buffer.Length)
    End While
    
    Console.WriteLine("Download Complete")
End Using

也可以用Do...Loop While写法,逻辑更贴近C#的先执行赋值再判断的模式:

Using input = Await client.GetStreamAsync(video.Uri)
    Dim buffer = New Byte((16 * 1024) - 1) {}
    Dim read As Integer
    Dim totalRead = 0
    Console.WriteLine("Download Started")
    
    Do
        read = input.Read(buffer, 0, buffer.Length)
        If read > 0 Then
            output.Write(buffer, 0, read)
            totalRead += read
            Console.Write($"\rDownloading {totalRead}/{totalByte} ...")
        End If
    Loop While read > 0
    
    Console.WriteLine("Download Complete")
End Using

内容的提问来源于stack exchange,提问作者shakydd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 20:16:04