直接用WebClient下载不就行了吗,干嘛还要定义一个WebRequest如下
using System.Net;
WebClient web = new WebClient();
private void button1_Click(object sender, EventArgs e)//下载
{
string app = "http://www.java.net/download/jdk6/6u10/promoted/b28/binaries/jdk-6u10-rc-bin-b28-windows-i586-p-21_jul_2008.exe";
string filename = "D:\\JDK6.exe";
web.DownloadFileCompleted += new AsyncCompletedEventHandler(web_DownloadFileCompleted);
web.DownloadProgressChanged += new DownloadProgressChangedEventHandler(web_DownloadProgressChanged);
web.DownloadFileAsync(new Uri(app), filename);
}
private void button2_Click(object sender, EventArgs e)//取消
{
web.CancelAsync();
}
void web_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
label1.Text = string.Format("开始下载文件... 已下载:{0}Mb 剩余:{1}Mb 已完成:{2}%",
e.BytesReceived / 1024 / 1024,
e.TotalBytesToReceive / 1024 / 1024,
e.ProgressPercentage.ToString("N2"));
}
void web_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
if (e.Cancelled)
label1.Text = "下载取消";
else
label1.Text = "下载完毕";
}
你把下载下来的19.9K的文件,改成 .html, 用ie,或者文本编辑器打开看一下。
我感觉这个大小,像个 html 的错误页面。
如果是错误页面,打开看看就知道哪里错了~
--------
string URLAddress = URL.Substring(0, n);
这时, URLAddress 已经被截断了
变成:
http://www.java.net/download/jdk6/6u10/promoted/b28/binaries/
了
这个 url 下载下来正好是19.9k
你直接
WebRequest myre = WebRequest.Create(app);
应该就好了
如果不知道链接就先分析html文件获得链接,然后下载。
文件下载的代码:
WebClient wc = new WebClient(); //创建网络通信实例
byte[] by = new byte[32]; //接收数据的数组
FileStream fs = new FileStream(filepath, FileMode.Create, FileAccess.Write); //创建文件
BinaryWriter bw = new BinaryWriter(fs);
while ((by = wc.DownloadData(dz)) != null) //写文件
{
bw.Write(by, 0, by.Length);
}
FileInfo f = new FileInfo(filepath);
f.MoveTo(filepath.Remove(filepath.LastIndexOf(".temp")) + ".swf"); //更名
bw.Close();
fs.Close(); //关闭数据流
ric.AppendText(filepath + "下载完毕");
WebRequest.Create(URL);
client.DownloadFile(URL, fileName);
//DownloadFile方法执行完后,文件已经下载到本地了,后面的代码是另一种下载方法,可以注释掉.
//文件大的话DownloadFile方法会卡死,有个异步下载方法DownloadFileAsync
用Response对象吧