从WebResponse获取文件(在本例中为.PDF,但任何文件都可以)的最佳方法是什么,并将其放入MemoryStream?使用WebResponse中的.GetResponseStream()获取Stream对象,但是如果要将该Stream转换为特定类型的流,您会怎么做?
在测试时我发现SoloBold的答案存在严重问题.当使用它来读取经由一个文件FtpWebRequest
到一个MemoryStream
它间歇地未能读取整个流到内存中.我跟踪到Peek()
有时在第一个1460字节之后返回-1,即使a Read()
会成功(文件明显大于此).
相反,我提出以下解决方案:
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