Error “This stream does not support seek operations” in C#

后端 未结 7 831
梦毁少年i
梦毁少年i 2020-12-01 07:36

I\'m trying to get an image from an url using a byte stream. But i get this error message:

This stream does not support seek operations.<

7条回答
  •  没有蜡笔的小新
    2020-12-01 07:40

    You can't reliably ask an HTTP connection for its length. It's possible to get the server to send you the length in advance, but (a) that header is often missing and (b) it's not guaranteed to be correct.

    Instead you should:

    1. Create a fixed-length byte[] that you pass to the Stream.Read method
    2. Create a List
    3. After each read, call List.AddRange to append the contents of your fixed-length buffer onto your byte list

    Note that the last call to Read will return fewer than the full number of bytes you asked for. Make sure you only append that number of bytes onto your List and not the whole byte[], or you'll get garbage at the end of your list.

提交回复
热议问题