简体   繁体   English

将流转换为字节数组

[英]Convert Stream to Byte Array

I created a simple extension to convert a Stream to Byte array: 我创建了一个简单的扩展以将Stream转换为Byte数组:

public static Byte[] ToByte(this Stream value) 
{
  if (value == null)
    return null;

  if (value is MemoryStream)
  {
    return ((MemoryStream)value).ToArray();
  }
  else 
  {
     using (MemoryStream stream = new MemoryStream()) 
     {
          value.CopyTo(stream);
          return stream.ToArray();
      }
  }

}

This works fine the first time I use it ... 第一次使用时效果很好...

If I use it a second time on the same stream the resulting Byte[] is Byte[0]. 如果我在同一流上第二次使用它,则结果Byte []为Byte [0]。

I debugged and I think this happens because after the first conversion the Stream index goes to the end of the stream. 我进行了调试,并且认为发生这种情况是因为在第一次转换之后,Stream索引将转到流的末尾。

What is the correct way to fix this? 解决此问题的正确方法是什么?

As you say, you are at the end of the stream after the first read. 就像您说的那样,您在第一次读取后就位于流的结尾。 Thus, you need to reset the memory stream with: 因此,您需要使用以下命令重置内存流:

stream.Seek(0, SeekOrigin.Begin);

Or 要么

stream.Position = 0;

Before reading it again. 在再次阅读之前。 Note that CanSeek on the stream must be true for either approach to work. 请注意,对于两种工作方式,流上的CanSeek必须为true。 MemoryStream is fine, some other streams will have this set to false. MemoryStream很好,其他一些流会将其设置为false。

将流索引设置为开头。

stream.Seek(0, SeekOrigin.Begin);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM