There is a serious issue with SoloBold's answer that I discovered while testing it. When using it to read a file via an FtpWebRequest
into a MemoryStream
it intermittently failed to read the entire stream into memory. I tracked this down to Peek()
sometimes returning -1 after the first 1460 bytes even though a Read()
would have succeeded (the file was significantly larger than this).
Instead I propose the solution below:
MemoryStream memStream;
using (Stream response = request.GetResponseStream()) {
memStream = new MemoryStream();
byte[] buffer = new byte[1024];
int byteCount;
do {
byteCount = stream.Read(buffer, 0, buffer.Length);
memStream.Write(buffer, 0, byteCount);
} while (byteCount > 0);
}
// If you're going to be reading from the stream afterwords you're going to want to seek back to the beginning.
memStream.Seek(0, SeekOrigin.Begin);
// Use memStream as required
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…