【发布时间】:2011-10-16 21:35:47
【问题描述】:
这里说 msdn.microsoft.com/en-us/library/system.io.stream.read.aspx Stream.Read 和 Stream.Write 方法都自动推进流中的位置/偏移量,所以为什么http://msdn.microsoft.com/en-us/library/system.io.stream.read.aspx 和 http://msdn.microsoft.com/en-us/library/system.io.filestream.read.aspx 这里的示例手动更改偏移量?
如果您知道流的大小,是否只在循环中设置偏移量,如果您不知道大小并使用缓冲区,则将其设置为 0?
// Now read s into a byte buffer.
byte[] bytes = new byte[s.Length];
int numBytesToRead = (int) s.Length;
int numBytesRead = 0;
while (numBytesToRead > 0)
{
// Read may return anything from 0 to 10.
int n = s.Read(bytes, numBytesRead, 10);
// The end of the file is reached.
if (n == 0)
{
break;
}
numBytesRead += n;
numBytesToRead -= n;
}
和
using (GZipStream stream = new GZipStream(new MemoryStream(gzip), CompressionMode.Decompress))
{
const int size = 4096;
byte[] buffer = new byte[size];
using (MemoryStream memory = new MemoryStream())
{
int count = 0;
do
{
count = stream.Read(buffer, 0, size);
if (count > 0)
{
memory.Write(buffer, 0, count);
}
}
while (count > 0);
return memory.ToArray();
}
}
【问题讨论】:
-
Stream 中的内部偏移量与您在缓冲区和流之间读取/写入数据时需要关心的偏移量/长度之间存在差异,可能还有 2. 流。
-
@nos:
2.是日耳曼语:说英语(实际上也包括其他语言)的人不会看到它的意思是“第二”。请改用2nd或second -
@IgnacioVazquez-Abrams:所以现在 Opera 是我的操作系统 - 哈哈。 Chrome/FF 确实可以在同一系统上渲染它。 (另外:我怪你试图通过 &zwsp; -es 欺骗来规避 cmets 的最小长度政策)