Direct Streaming方法CopyTo找不到结尾



我正在使用此方法读取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:Usersmini_dataset.txt")
While True
If stream.CanRead Then
stream.CopyTo(output)
Else
Exit While
End If
End While
End Sub

但这个过程最终是一个无休止的循环(我想(——至少在我看来,似乎找不到流的尽头。我可以在几秒钟后中断这个过程,所有数据都在.txt文件中。知道我能做些什么来让直接流到文件的方法工作吗?

流。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

如果这个过程需要一些时间,并且你需要报告它的进度,你可以使用缓冲区读取流(我没有添加任何错误检查,但当然应该使用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

最新更新