问题
This method that I wrote was working fine a week ago but now it downloads an incomplete file. The original file is nearly 10mb but the file that is being downloaded is 2k. My code is basically this
Dim URL as string = "http://www.cqc.org.uk/sites/default/files/cqc_locations_export.csv"
Dim path as string = "C:\temp"
Dim webClient As New WebClient
webClient.Headers.Add("user-agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12 (.NET CLR 3.5.30729)")
webClient.DownloadFile(URL, path)
Any idea what is going wrong here ?
Cheers
回答1:
This is not my area, but you may be missing the size of the file, if it's binary, char encoding and other header data. Also, this 2k of file maybe a part of the file or metadata.
回答2:
The Second argument to DownloadFile
requires a full filename not just a path (and the root of the C:\
drive is protected on windows 7 so the method may throw an exception if you try to write here)
Note: Don't forget to dispose of the webclient when done.
Note 2: I would suggest you should avoid naming collisions by using names other than the .NET class names. Don't forget VB is case insensitive (unlike C#)
The following works fine for me:
Dim URL As String = "http://www.cqc.org.uk/sites/default/files/cqc_locations_export.csv"
Dim filename As String = "C:\temp\temp.csv"
Using wc As New WebClient
wc.Headers.Add("user-agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12 (.NET CLR 3.5.30729)")
wc.DownloadFile(URL, filename)
End Using
回答3:
It could be a problem with the site that is hosting the file, or how that site handles GET requests. I had the same problem downloading a URI I had shared from DropBox. The file was about 3 MB, but only about the first 112 KB was downloaded. When I downloaded the same file from Screencast.com, the whole file was downloaded.
回答4:
On ground you may want to try three things :
- Run your application with Admin rights as C drive is protected in Windows 7 and above.
- Temporary stop your antivirus program and try downloading again.
- Only dispose webClient when download is complete (On DownloadFileCompleted Event)
回答5:
The docs seems to suggest either (two different variations)
Dim client As New WebClient()
or
Dim client As WebClient
来源:https://stackoverflow.com/questions/11881893/webclient-downloads-an-incomplete-file