如何将 WebResponse 放入内存流? [英] How do I put a WebResponse into a memory stream?

查看:29
本文介绍了如何将 WebResponse 放入内存流?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从 WebResponse 获取文件(在本例中为 .PDF,但任何文件都可以)并将其放入 MemoryStream 的最佳方法是什么?使用 WebResponse 中的 .GetResponseStream() 获取一个 Stream 对象,但是如果您想将该 Stream 转换为特定类型的流,您会怎么做?

What is the best way to get a file (in this case, a .PDF, but any file will do) from a WebResponse and put it into a MemoryStream? Using .GetResponseStream() from WebResponse gets a Stream object, but if you want to convert that Stream to a specific type of stream, what do you do?

推荐答案

SoloBold 的 答案 我在测试时发现的.当使用它通过 FtpWebRequest 将文件读入 MemoryStream 时,它间歇性地无法将整个流读入内存.我将其跟踪到 Peek() 有时在前 1460 个字节后返回 -1,即使 Read() 会成功(文件明显大于此).

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

这篇关于如何将 WebResponse 放入内存流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆