代码之家  ›  专栏  ›  技术社区  ›  redtuna

为什么BufferedStream.Write会抛出“此流不支持查找操作”?

  •  8
  • redtuna  · 技术社区  · 14 年前

    这个让我困惑。当我不叫它的时候,我就犯了一个关于seek的错误?

    我有这样的代码:

    // 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)
    ...
    

    流的类型为 System.IO.BufferedStream

    使用更多信息编辑:

    sizeof(uint)==msg.length
    stream = new BufferedStream(new NetworkStream(socket), 1024)

    编辑:

    就这样!当一个人可以在一张纸上读写的时候 NetworkStream ,当切换到 BufferedStream 有必要为阅读和写作单独设置一个。很明显,你可以打电话给 在同一个套接字上构造两次。

    2 回复  |  直到 13 年前
        1
  •  9
  •   Justin Niessner    14 年前

    问题在于BufferedStream的内部工作(以及您可能在尝试写入之前使用BufferedStream进行读取的事实)。

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


    我们是在乞求写缓冲区吗?

    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(), 是什么导致了你的错误 .

        2
  •  4
  •   Hans Passant    14 年前

    推荐文章