Question : VB.NET: optimal buffer size and speed issues with  IO.FileStream

Hi X-perts,

i am using the following code for file downloading. What are the optimal buffer size settings from the d/l speed point?

Can I improve it somehow?

Thanks
Code Snippet:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
Dim byteTransferRate As Integer = 4096 '4096 bytes = 4 KB
        Dim bytes(byteTransferRate - 1) As Byte
        Dim bytesRead As Integer = 0 'Indicates how many bytes were read 
        Dim totalBytesRead As Long = 0 'Indicates how many total bytes were read
        Dim contentLength As Long = 0 'Indicates the length of the file being downloaded
        Dim url As String = "http://www.mysite.com/dl.php"

        Dim request As HttpWebRequest = DirectCast(System.Net.HttpWebRequest.Create(url), HttpWebRequest)

        Dim response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)

        'Read the content length
        contentLength = CLng(response.GetResponseHeader("Content-Length"))
       
        'Create a new file to write the downloaded data to
        Dim fs As New IO.FileStream(destination, IO.FileMode.Create, IO.FileAccess.Write)

        Dim s As IO.Stream = response.GetResponseStream()

        Do
            'Read from the stream
            bytesRead = s.Read(bytes, 0, bytes.Length)
            If (contentLength < 100) Then
                msgResponse = msgResponse & Encoding.ASCII.GetString(bytes)
            End If
            If bytesRead > 0 Then

                totalBytesRead += bytesRead

                'Write to file
                If (contentLength >= 100) Then fs.Write(bytes, 0, bytesRead)

            End If
            Me.ProgressBarAdv1.Value = Math.Round(100 * totalBytesRead / contentLength, 0)
            Application.DoEvents()
        Loop While bytesRead > 0

Answer : VB.NET: optimal buffer size and speed issues with  IO.FileStream

I've found that I can increase the size to eliminate overhead (over frequent progress calculations and updates,) but after a certain point it doesn't make much difference.  100-200K works well for me.  Your mileage may vary.
Random Solutions  
 
programming4us programming4us