Direct Streaming Method CopyTo 找不到结尾

Direct Streaming Method CopyTo does not find the end

我正在用这个方法读一个SSE

    Public Shared Sub ReadStreamForever(ByVal stream As Stream)
    Dim encoder = New UTF8Encoding()
    Dim buffer = New Byte(2047) {}
    Dim counter As Integer = 0
    While True
        If stream.CanRead Then
            Dim len As Integer = stream.Read(buffer, 0, 2048)
            counter = counter + 1
            If len > 0 Then
                Dim text = encoder.GetString(buffer, 0, len)
                SSEApplication.Push(text) 'Here I collect the text slices to a List(of string) object
            Else
                Exit While
            End If
        Else
            Exit While
        End If
    End While
    SSEApplication.writer() 'Here I write the content to a .txt file
End Sub

使用我的示例数据大约需要 2 秒。我不想将流读入内存并尝试了这种方法

Public Shared Sub ReadStreamForever1(ByVal stream As Stream)

    Dim output As FileStream = File.OpenWrite("C:\Users\mini_dataset.txt")
    While True
        If stream.CanRead Then
            stream.CopyTo(output)
        Else
            Exit While
        End If
    End While
End Sub

但是这个过程以无限循环结束(我猜)至少对我来说它看起来无法找到流的结尾。我可以在几秒钟后中断该过程,所有数据都在 .txt 文件中。知道我可以做些什么来使直接流到文件方法起作用吗?

Stream.CanRead 告诉你流是否支持读取。由于它显然是可读的,While True 将永远持续下去。
让我们验证是否输出 Stream.CanWrite 而不是

Public Shared Sub ReadStreamForever1(ByVal stream As Stream)
    Using output As FileStream = File.OpenWrite("[Output file path]")
        If output.CanWrite Then
            stream.CopyTo(output)
        End If
    End Using
End Sub

如果该过程需要一些时间并且您需要报告其进度,您可以 read the stream using a buffer(我没有添加任何错误检查,但当然应该使用 try/catch 块):
(这里以一个ProgressBar常用的100部分划分)

Public Sub ReadStreamForever1(ByVal stream As Stream)
    Dim BufferLength As Integer = 81920 'As the default stream buffer
    Dim Buffer(BufferLength) As Byte
    Dim BytesRead As Long = 0L

    Using output As FileStream = File.OpenWrite("[Output file path]")
        If output.CanWrite Then
            Dim Part As Long = stream.Length \ 100
            Dim PartCount As Integer = 0
            Dim read As Integer = 0
            Do
                read = stream.Read(Buffer, 0, BufferLength)
                If read = 0 Then Exit Do
                If (BytesRead / Part > PartCount) Then
                    PartCount += 1
                    'ReportWriteProgress(PartCount)
                End If
                output.Write(Buffer, 0, read)
                BytesRead += read
            Loop
        End If
    End Using
End Sub