How do I put a WebResponse into a memory stream?

后端 未结 3 1546
花落未央
花落未央 2020-12-20 14:27

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 WebRespon

3条回答
  •  余生分开走
    2020-12-20 15:08

    I found the following at http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/eeeefd81-8800-41b2-be63-71acdaddce0e/

        Dim request As WebRequest
        Dim response As WebResponse = Nothing
        Dim s As Stream = Nothing
        Dim fs As FileStream = Nothing
        Dim file As MemoryStream = Nothing
    
        Dim uri As New Uri(String.Format("http://forums.microsoft.com/forums/ShowPost.aspx?PostID=2992978&SiteID=1"))
        request = WebRequest.Create(uri)
        request.Timeout = 10000
        response = request.GetResponse
        s = response.GetResponseStream
    
        '2 - Receive file as memorystream
        Dim read(256) As Byte
        Dim count As Int32 = s.Read(read, 0, read.Length)
        File = New MemoryStream
        Do While (count > 0)
            File.Write(read, 0, count)
            count = s.Read(read, 0, read.Length)
        Loop
        File.Position = 0
        'Close responsestream
        s.Close()
        response.Close()
    
        '3 - Save file
        fs = New FileStream("c:\test.html", FileMode.CreateNew)
        count = file.Read(read, 0, read.Length)
        Do While (count > 0)
            fs.Write(read, 0, count)
            count = file.Read(read, 0, read.Length)
        Loop
        fs.Close()
        File.Close()
    

提交回复
热议问题