This is my C# code to download a ZIP file from my server. When I download I don’t receive the file, but it is partially downloaded.
public static void Download(String strURLFileandPath, String strFileSaveFileandPath)
{
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(strURLFileandPath);
HttpWebResponse ws = (HttpWebResponse)wr.GetResponse();
Stream str = ws.GetResponseStream();
byte[] inBuf = new byte[100000];
int bytesToRead = (int)inBuf.Length;
int bytesRead = 0;
while (bytesToRead > 0)
{
int n = str.Read(inBuf, bytesRead, bytesToRead);
if (n == 0)
break;
bytesRead += n;
bytesToRead -= n;
}
try
{
FileStream fstr = new FileStream(strFileSaveFileandPath, FileMode.OpenOrCreate, FileAccess.Write);
fstr.Write(inBuf, 0, bytesRead);
str.Close();
fstr.Close();
}
catch (Exception e) {
MessageBox.Show(e.Message);
}
}
I thing the problem is happening here
byte[] inBuf = new byte[100000];
When I increase the value of byte[] inBuf = new byte[100000]; to byte[] inBuf = new byte[10000000];
The file is downloading perfectly.
But my problem is if I download files larger than 50 MB (eg.: 200 MB) .
This method is not good.
Can anyone tell me how can I fix this problem?
You could copy directly from stream to stream using the Stream.CopyTo() method.
Or even simpler: Use the WebClient class and its
DownloadFilemethod to download the file. This solution would replace your complete method: