为什么BufferedStream.Write抛出“此流不支持搜索操作"? [英] Why would BufferedStream.Write throw "This stream does not support seek operations"?

查看:281
本文介绍了为什么BufferedStream.Write抛出“此流不支持搜索操作"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这使我感到困惑.当我什至没有打电话的时候,我就得到了关于寻找的错误?

This one puzzles me. I get an error about seek when I'm not even calling it?

我的代码看起来像这样:

I have code that looks something like this:

// send 42
uint value = 42;
byte[] msg = BitConverter.GetBytes(value);
stream.Write(msg, 0, sizeof(uint));

我得到了这个异常:

System.NotSupportedException was unhandled
Message="This stream does not support seek operations."
Source="System"
StackTrace:
   at System.Net.Sockets.NetworkStream.Seek(Int64 offset, SeekOrigin origin)
   at System.IO.BufferedStream.FlushRead()
   at System.IO.BufferedStream.Write(Byte[] array, Int32 offset, Int32 count)
...

stream的类型为System.IO.BufferedStream.可能会发生什么?

stream is of type System.IO.BufferedStream. What could possibly be going on?

编辑更多信息:

sizeof(uint)==msg.length在这种情况下.
流被声明为stream = new BufferedStream(new NetworkStream(socket), 1024)

sizeof(uint)==msg.length in this case.
The stream is declared as stream = new BufferedStream(new NetworkStream(socket), 1024)

就是这样!虽然一个人可以在单个NetworkStream上进行读写,但切换到BufferedStream时,必须有一个单独的读写器.显然,可以在同一套接字上两次调用NetworkStream构造函数以获取该信息.

That was it! While one can read and write on a single NetworkStream, when switching to a BufferedStream it is necessary to have a separate one for reading and writing. One can apparently just call the NetworkStream constructor twice on the same socket to get that.

如果可以的话,我会接受贾斯汀和汉斯的回答,因为一个让我确切地了解出了什么问题,另一个让我找到了解决方案.谢谢大家!

I'd accept both Justin and Hans' answers if I could, because one let me exactly understand what was wrong, and the other led me to the solution. Thanks everyone!

推荐答案

问题在于BufferedStream的内部工作原理(以及您可能在尝试写入BufferedStream之前已从中读取数据的事实).

The problem lies in the inner workings of BufferedStream (and the fact that you may have used the BufferedStream to Read from prior to attempting to write to it).

当您尝试写入BufferedStream时,在验证参数之后,将按以下顺序检查内容(所有代码均通过Reflector从Framework中提取):

When you try to Write to a BufferedStream, after validating your parameters, things are checked in this order (all code pulled from the Framework via Reflector):

我们在请求写缓冲区吗?

Are we at the begging of the write buffer?

if(this._writePos == 0)

是否允许写入基础流?

if(!this._s.CanWrite) // throw error

读取缓冲区是否为空?

if(this._readPos < this._readLen)
{
    // FlushRead() will attempt to call Seek()
    this.FlushRead();
}


如果读取缓冲区中有未读取的数据,则在写入之前尝试进行刷新. FlushRead()调用Seek(),这是导致您出错的原因.

这篇关于为什么BufferedStream.Write抛出“此流不支持搜索操作"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆