Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

vb.net - How do I put a WebResponse into a memory 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...