Is it safe to use Stream.Seek when a BinaryReader is open?

前端 未结 3 621
长发绾君心
长发绾君心 2021-01-05 02:50

Because of the under the hood buffering strategy of BinaryReader, it is unclear to me whether is it ok or not to read an offset stored in a stream, then reposition the strea

3条回答
  •  礼貌的吻别
    2021-01-05 03:28

    I would say that it is not always safe (although it might be safe in some cases).

    The Microsoft documentation for BinaryReader.BaseStream explicitly states:

    Using the underlying stream while reading or while using the BinaryReader can cause data loss and corruption. For example, the same bytes might be read more than once, bytes might be skipped, or character reading might become unpredictable.

    So I would avoid it.

    (Interestingly, there's a BinaryWriter.Seek() method, but no BinaryReader.Seek().)

提交回复
热议问题