Download files using WebRequest

Posted on 2013-12-11
Last Modified: 2013-12-26
webclient.DownloadFile times out and fails.

This codes below appears to work, but the resulting files are all the same size ( 39kb) , and
are not complete.  
Can someone see the error?

         private static void DownloadFile(Uri remoteUri , string localPath)
            var request = (HttpWebRequest)WebRequest.Create(remoteUri);
            request.Timeout = 30000;
            request.AllowWriteStreamBuffering = false;

            using (var response = (HttpWebResponse)request.GetResponse())
            using (var s = response.GetResponseStream())
            using (var fs = new FileStream(localPath, FileMode.Create))
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = s.Read(buffer, 0, buffer.Length)) > 0)
                    fs.Write(buffer, 0, bytesRead);
                    bytesRead = s.Read(buffer, 0, buffer.Length);
Question by:awalkinthepark

Author Comment

ID: 39712969
nevermind - I have webclient.DownloadFile working.
But a solution could be worth posting.
LVL 75

Accepted Solution

käµfm³d   👽 earned 500 total points
ID: 39713035
Add a call to Flush outside of your while loop.



while ((bytesRead = s.Read(buffer, 0, buffer.Length)) > 0)
    fs.Write(buffer, 0, bytesRead);
    bytesRead = s.Read(buffer, 0, buffer.Length);



Open in new window


Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: Ivo
C# And Nullable Types Since 2.0 C# has Nullable(T) Generic Structure. The idea behind is to allow value type objects to have null values just like reference types have. This concerns scenarios where not all data sources have values (like a databa…
In order to hide the "ugly" records selectors (triangles) in the rowheaders, here are some suggestions. Microsoft doesn't have a direct method/property to do it. You can only hide the rowheader column. First solution, the easy way The first sol…
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit If you want to manage em…
In a recent question ( here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…

749 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question