且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

NetworkStream 不支持查找操作

更新时间:2021-10-17 23:18:53

你是从这个流中读到最后吗?如果是这样,我建议您将整个内容复制到 MemoryStream 中,然后您可以在 that 上查找您的内容.在 .NET 4 中,使用 Stream 尤其容易.复制到:

Are you reading from this stream until the end? If so, I suggest you just copy the entire contents into a MemoryStream, then you can seek on that to your heart's content. In .NET 4 it's particularly easy with Stream.CopyTo:

MemoryStream dataCopy = new MemoryStream();
using (var clientRequestStream = _tcpClient.GetStream())
{
    clientRequestStream.CopyTo(dataCopy);
}
dataCopy.Position = 0;
var requestHeader = dataCopy.GetUtf8String();

NetworkStream 不可搜索是有意义的——它只是服务器提供给您的数据流.除非您可以告诉 服务器 倒带(这仅在某些情况下才有意义),否则除非某些东西缓冲了您需要倒带的尽可能多的数据,否则无法寻找 - 这基本上就是复制到 MemoryStream 确实如此,以相当蛮力的方式.

It makes sense for NetworkStream not to be seekable - it's just a stream of data that a server is giving to you. Unless you can tell the server to rewind (which only even makes sense in some situations) there's no way of seeking unless something buffers as much data as you need to rewind - which is basically what copying to a MemoryStream does, in a pretty brute-force fashion.