日期:2011-06-25  浏览次数:20386 次

一.概述:   
    本文通过一个实例向大家介绍用C# Builder进行Internet通讯编程的一些基本知识。我们知道.Net类包含了请求/响应层、应用协议层、传输层等层次。在本程序中,我们运用了位于请求/响应层的WebRequest类以及WebClient类等来实现高抽象程度的Internet通讯服务。本程序的功能是完成文件的下载。
二.实现原理:   
    程序实现的原理比较简单,主要用到了WebClient类和FileStream类。其中WebClient类处于System.Net名字空间中,该类的主要功能是提供向URI标识的资源发送数据和从URI标识的资源接收数据的公共方法。我们利用其中的DownFile()方法将文件下载到本地。然后用FileStream类的实例对象以数据流的方式将文件数据写入本地文件。这样就完成了文件的下载。
三.实现步骤:
    1.首先,打开C# Builder,File->New->C# Application,Name这里我们设为"download"。
    2.主界界的设置。text设为“文件下载”,StartPosition设为CenterScreen,MaximizeBox设为False,我们在主窗体上添加如下控件:两个标签控件label1,label2、一个文本框控件textBox1、一个按钮控件button1以及一个进度条控件progressBar1。
    label1:text为URL;Label2:text为下载进度;textBox1:text设为空;button1:text设为下载;
    3.程序的编码
     //过程downfile,用于完成文件的下载
  private void downfile()
  {
   string FileName;
   WebClient DownFile=new WebClient();
   long fbytes;
   if (textBox1.Text!="")
   {
     saveFileDialog1.ShowDialog();
     FileName=saveFileDialog1.FileName;
     if(FileName!= "")
     {
      //取得文件大小
      WebRequest wr_request=WebRequest.Create(textBox1.Text);
      WebResponse wr_response=wr_request.GetResponse();
      fbytes=wr_response.ContentLength;
      progressBar1.Maximum=(int)fbytes;
      progressBar1.Step=1;
      wr_response.Close();
                           //开始下载数据
      DownFile.DownloadData(textBox1.Text);
      Stream strm = DownFile.OpenRead(textBox1.Text);
      StreamReader reader = new StreamReader(strm);
      byte[] mbyte = new byte[fbytes];
      int allmybyte = (int)mbyte.Length;
      int startmbyte = 0;
      while(fbytes>0)
      {
     int m = strm.Read(mbyte,startmbyte,allmybyte);
     if(m==0) break;
     startmbyte+=m;
     allmybyte-=m;
     progressBar1.value+=m;
      }
      FileStream fstrm = new FileStream(FileName,FileMode.OpenOrCreate,FileAccess.Write);
      fstrm.Write(mbyte,0,startmbyte);
      strm.Close();
      fstrm.Close();
      progressBar1.value=progressBar1.Maximum;
     }
   } else
   {
      MessageBox.Show("没有输入要下载的文件!");
   }
  }

     //双击“下载”按钮,输入以下代码:
     Thread th = new Thread(new ThreadStart(downfile));
     th.Start();

      //完整的代码如下:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Net;
using System.IO;
using System.Threading;

namespace download
{
 /// <summary>
 /// Summary description for WinForm.
 /