• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 243
  • Last Modified:

Download files using WebRequest

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?
Thanks

         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);
                }
            }
        }
0
awalkinthepark
Asked:
awalkinthepark
1 Solution
 
awalkintheparkAuthor Commented:
nevermind - I have webclient.DownloadFile working.
But a solution could be worth posting.
Thanks
0
 
käµfm³d 👽Commented:
Add a call to Flush outside of your while loop.

e.g.

...

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

fs.Flush();

...

Open in new window

0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now