NetworkStream doesn't support seek operations

拥有回忆 提交于 2019-12-02 02:47:48

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();

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.

As you've discovered, NetworkStream is not seekable.
NetworkStream feeds you data directly from the network.

You should read the data into a MemoryStream and re-use that.

Assuming you don't want to properly rewrite your GetUtf8String method to not require seek...

The easiest approach would be to copy stream to MemoryStream first and than you have stream you can seek as much as you want. Stream.CopyTo will take care of copying (.Net4+)

Note that you need to seek resulting MemoryStream back by setting Position property to 0 (copiedStream.Position=0) or cloning the stream by creating new one (preferably read only) based on buffer and length of first memory stream.

You won't be able to set clientRequestStream.Position = 0 because NetworkStream is forward-only. See here: http://msdn.microsoft.com/en-us/library/system.net.sockets.networkstream.position.aspx

Be careful about thinking of NetworkStream in the same way as regular streams. Things like Peek() for example on a StreamReader can cause your application to block.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!