//source 元文件地址 fileName 保存地址
private void DownloadFile(string source, string fileName)
{
try
{
//WebProxy _WP = new WebProxy(ProxyName, ProxyPort);
FileStream localStream;
//create a web Httprequest
HttpWebRequest wReq = (HttpWebRequest)HttpWebRequest.Create(source);
//set the address and port of the proxy server
WebProxy wp = new WebProxy("192.168.11.8", 8080);
wp.BypassProxyOnLocal = true;
ICredentials credentials = new NetworkCredential("sun", "sun");
wp.Credentials = credentials;
//set the web request's proxy server
wReq.Proxy = wp;
//create a web Httpresponse
HttpWebResponse wResp = (HttpWebResponse)wReq.GetResponse();
//write the response to a stream
Stream respStream = wResp.GetResponseStream();
//create a new file to receive the response stream
localStream = new FileStream(fileName, FileMode.Append, FileAccess.Write);
BinaryReader reader = new BinaryReader(respStream);
//set the receive binary buffer
const int BufferSize = 102400;
byte[] buffer = new Byte[BufferSize];
bool bFinished = false;
int dataRead;
//just write the buffer to the binaryReader again and again
do
{
try
{
dataRead = reader.Read(buffer, 0, BufferSize);
if (dataRead == 0)
bFinished = true;
localStream.Write(buffer, 0, dataRead);
}
catch
{
localStream.Close();
respStream.Close();
}
} while (!bFinished);
//close all file stream
localStream.Close();
respStream.Close();
//ShowLog("Download finished");
}
catch (Exception ex)
{
throw new Exception("下載失敗,原因是:" + ex.Message, ex);
}
}