Search code examples
c#.netdownloadhttpwebrequest

Incomplete/Corrupted downloaded files


I have made this little tool wich goes through a list of image links and download them to the hard drive, however, some of the pictures are incomplete (Check this picture) and they don't even raise an exception. The code below shows the download method I'm using in my tool.

private void Download(string url)
{
    try
    {
        HttpWebRequest Request = WebRequest.Create(url) as HttpWebRequest;
        Request.Method = WebRequestMethods.Http.Get;
        Request.Timeout = 60 * 1000;
        FileInfo ImageFile = new FileInfo(Path.Combine(BaseDirectory, Path.GetFileName(url)));
        if (!ImageFile.Exists)
        {
            using (HttpWebResponse Response = Request.GetResponse() as HttpWebResponse)
            {
                if (Response.StatusCode.Equals(HttpStatusCode.OK))
                {
                    using (FileStream FStream = new FileStream(ImageFile.FullName, FileMode.Create, FileAccess.Write, FileShare.None, 4096))
                        Response.GetResponseStream().CopyTo(FStream, 4096);
                }
            }
        }
    }
    catch (Exception e)
    {
        Console.WriteLine("Error Downloading: {0}\r\nMessage: {1}", url, e.Message);
    }
}

I can't figure out whether the problem is on the server side or there is something wrong with my code, so what do you think?


Solution

  • Have you tried calling Flush() after you've read the data? It looks like the last part of the stream isn't being written out.