从WebResponse获取文件(在这种情况下是.PDF,但是任何文件都会这样做)的最佳方式是将其放入MemoryStream中?从WebResponse使用.GetResponseStream()获取一个Stream对象,但是如果要将该Stream转换为特定类型的流,那么你该怎么做?
我在测试时发现的SoloBold的
answer有一个严重的问题.当使用它通过FtpWebRequest将文件读入MemoryStream时,它间歇地无法将整个流读入内存.我跟踪到Peek()有时在第一个1460字节之后返回-1,即使一个Read()将成功(该文件明显大于此).
原文链接:https://www.f2er.com/vb/255141.html相反,我提出以下解决方案:
MemoryStream memStream; using (Stream response = request.GetResponseStream()) { memStream = new MemoryStream(); byte[] buffer = new byte[1024]; int byteCount; do { byteCount = stream.Read(buffer,buffer.Length); memStream.Write(buffer,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