Go homepage(回首页) Upload pictures (上传图片) Write articles (发文字帖)
The author:(作者)delvpublished in(发表于) 2014/1/6 9:14:25 用Visual,C#实现文件下载_[Asp.Net教程]
} #endregion /// /// 应用程序的主入口点。 /// [STAThread] static void Main() { Application.Run(new Form1()); } private void StartDownload() { Start.Enabled = false; string URL = srcAddress.Text; int n = URL.LastIndexOf("?"); string URLAddress = URL; //string URLAddress = URL.Substring(0,n); string fileName = URL.Substring(n+1,URL.Length-n-1); string Dir = tarAddress.Text; string Path = Dir+fileName; try { WebRequest myre=WebRequest.Create(URLAddress); } catch(WebException exp) { MessageBox.Show(exp.Message,"Error"); } try { statusBar.Text = "开始下载文件..."; client.DownloadFile(URLAddress,fileName); Stream str = client.OpenRead(URLAddress); //StreamReader reader = new StreamReader(str); ,这句没有什么必要!个人认为 byte[] mbyte = new byte[100000]; int allmybyte = (int)mbyte.Length; int startmbyte = 0; statusBar.Text = "正在接收数据..."; //写入到BYTE数组中,起缓冲作用 while(allmybyte>0) { int m = str.Read(mbyte,startmbyte,allmybyte); if(m==0) break; startmbyte+=m; allmybyte-=m; } FileStream fstr = new FileStream(Path,FileMode.OpenOrCreate,FileAccess.Write); fstr.Write(mbyte,0,startmbyte); str.Close(); fstr.Close(); statusBar.Text = "下载完毕!"; } catch(WebException exp) { MessageBox.Show(exp.Message,"Error"); statusBar.Text = ""; } Start.Enabled = true; } private void Start_Click(object sender, System.EventArgs e) { Thread th = new Thread(new ThreadStart(StartDownload)); th.Start(); } } }
赞