public static Int64 WriteBinaryFile(String url, String filePath)
{
Int64 bytesWritten = 0;
try
{
WebResponse objResponse;
objResponse = WebRequest.Create(url).GetResponse();
Byte[] ByteBucket = new Byte[objResponse.ContentLength];
BinaryReader readStream = new BinaryReader(objResponse.GetResponseStream());
FileStream fileToWrite = new FileStream(HttpContext.Current.Server.MapPath(filePath), FileMode.Create, FileAccess.Write);
Int32 currentBytesRead = 0;
Int32 totalBytesRead = 0;
Boolean done = false;
#region Use a buffer to prevent truncated files
while (!done)
{
currentBytesRead = readStream.Read(ByteBucket, 0, Convert.ToInt32(objResponse.ContentLength));
fileToWrite.Write(ByteBucket, 0, currentBytesRead);
totalBytesRead += currentBytesRead;
if (totalBytesRead == objResponse.ContentLength)
{
done = true;
}
}
#endregion
fileToWrite.Close();
bytesWritten = objResponse.ContentLength;
}
catch
{
bytesWritten = 0;
}
return bytesWritten;
}