title: How do I decide on a buffer size when downloading a file using HttpWebRequest and HttpWebResponse?
body: <p>I'm using HttpWebRequest / HttpWebResponse to download an image file from a remote server to my own web server. The code is working fine, but I don't know if the buffer size I've chosen is the optimum size for best performance.</p>
  
  <p>How would I go about choosing the right buffer size?</p>
  
  <p>My code is below - you can see it's currently using a buffer size of 4096 - that's just an arbitrary number I chose:</p>
  
  <pre><code>    ' Create the web request
      Dim myWebRequest As HttpWebRequest = HttpWebRequest.Create("http://www.petiquettedog.com/wp-content/uploads/2010/04/sadpug-300x225.jpg")
  
      ' Automatically decompress gzip/deflate compressed images. This line sets the Accept-Encoding header to "gzip, deflate"
      myWebRequest.AutomaticDecompression = DecompressionMethods.GZip or DecompressionMethods.Deflate
  
      Using myWebResponse As HttpWebResponse = myWebRequest.GetResponse()
          ' Download the image to disk
          Using streamIn As Stream = myWebResponse.GetResponseStream()
              Using streamOut As FileStream = File.Create(localFilePhysical)
                  Dim bufferSize As Integer = 4096
                  Dim bytes(bufferSize) As Byte
                  Dim numBytes As Integer
                  numBytes = streamIn.Read(bytes, 0, bufferSize)
                  While numBytes &gt; 0
                      streamOut.Write(bytes, 0, numBytes)
                      numBytes = streamIn.Read(bytes, 0, bufferSize)
                  End While
              End Using
          End Using
      End Using
  </code></pre>