#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.Substring(0,n); string fileName = URL.Substring(n+1,URL.Length-n-1); string Dir = tarAddress.Text; string Path = Dir+\ try { WebRequest myre=WebRequest.Create(URLAddress); } catch(WebException exp) { MessageBox.Show(exp.Message,\ } 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 = \正在接收数据...\ 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,\ statusBar.Text = \ } Start.Enabled = true; } private void Start_Click(object sender, system.EventArgs e) { Thread th = new Thread(new ThreadStart(StartDownload)); th.Start(); } } } 四.总结:
以上我通过一个实例向大家展示了如何用Visual C#实现网络文件的下载,我们不难发现用Visual C#进行Internet通讯编程是非常方便的。在上面的程序中,我们仅仅用到了WebClient类的一些方法,而WebClient类不光提供了网络文件下载的方法,还提供了文件上传的方法,有兴趣的读者不妨一试――用之实现一个文件上传器。同时这个程序只是一个非常简单的例子,程序下载完一个网页后,它所获得的仅仅是主页面的内容,并不能获得其中的图片、CSS等文件,所以要做出一个比较好的文件下载器还需读者进一步改进之。