MemoryStream.Read 不会将字节复制到缓冲区 - c#
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/376156/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MemoryStream.Read doesn't copy bytes to buffer - c#
提问by agnieszka
I don't really get it and it's driving me nuts. i've these 4 lines:
我真的不明白,这让我发疯。我有这 4 行:
Image img = Image.FromFile("F:\Pulpit\soa.bmp");
MemoryStream imageStream = new MemoryStream();
img.Save(imageStream, ImageFormat.Bmp);
byte[] contentBuffer = new byte[imageStream.Length];
imageStream.Read(contentBuffer, 0, contentBuffer.Length);
when debugging i can see the bytes values in imageStream. after imageStream.Read i check content of contentBuffer and i see only 255 values. i can't get why is it happening? there is nothing to do wrong in these few lines! if anyone could help me it would be greatly appreciated! thanks, agnieszka
调试时我可以看到 imageStream 中的字节值。在 imageStream.Read 之后,我检查 contentBuffer 的内容,我只看到 255 个值。我不明白为什么会这样?这几行没有什么可做的!如果有人可以帮助我,将不胜感激!谢谢, agnieszka
采纳答案by Andrew Kennan
Try setting imageStream.Position to 0. When you write to the MemoryStream it moves the Position after the bytes you just wrote so if you try to read there's nothing there.
尝试将 imageStream.Position 设置为 0。当您写入 MemoryStream 时,它会将 Position 移动到您刚写入的字节之后,因此如果您尝试读取,则那里什么也没有。
回答by Joel Lucsy
You need to reset the file pointer.
您需要重置文件指针。
imageStream.Seek( 0, SeekOrigin.Begin );
Otherwise you're reading from the end of the stream.
否则,您将从流的末尾阅读。
回答by BenAlabaster
Add:
添加:
imageStream.Position = 0;
right before:
就在之前:
imageStream.Read(contentBuffer, 0, contentBuffer.Length);
the 0 in your read instruction stands for the offset from the current position in the memory stream, not the start of the stream. After the stream has been loaded, the position is at the end. You need to reset it to the beginning.
读取指令中的 0 代表与内存流中当前位置的偏移量,而不是流的开头。流加载完毕后,位置在末尾。您需要将其重置为开头。
回答by Patrick Desjardins
Image img = Image.FromFile("F:\Pulpit\soa.bmp");
MemoryStream imageStream = new MemoryStream();
img.Save(imageStream, ImageFormat.Bmp);
byte[] contentBuffer = new byte[imageStream.Length];
imageStream.Position = 0;//Reset the position at the start
imageStream.Read(contentBuffer, 0, contentBuffer.Length);
回答by Jaime Bula
Just use
只需使用
imageStream.ToArray()
It works and it easier.
它有效而且更容易。