.NET1.1開發FTP客戶端

http://dev.csdn.net/author/banmuhuangci/eaebb4c64ff94af0b8565899f884f071.html

前面我的一篇文章提到使用CUTEFTP的FTP引擎製作.NET的FTP上傳客戶端,但是這是個很鬱悶的事情,首先,需要在註冊表中註冊這個COM,CUTEFTP的官方站提供了一段註冊表寫法的文章,這還好說。最關鍵的是,在使用這個組建的時候還需要註冊產品。不會有任何人希望用戶在用軟件的時候卻還要註冊別的公司的產品先。

前面之所以寫採用CUTEFTP的引擎做客戶端主要是爲了方便,在一臺已經安裝CUTEFTP的PC上使用還是很方便的,但是我們還是希望開發獨立的軟件。

實際上採用FTP進行文件傳輸在搞清楚FTP命令和數據連接方式後做起來也不是很難,畢竟FTP是一個公共的協議。

以下是本人寫的一個簡單的示例,其中的功能只有上傳文件,工作模式基本說明了FTP的原理,很容易從例子中推敲出其他FTP的功能。  在近幾天的BLOG文章中將陸續推出一些資料信息。

另外,.NET2.0中在System.Net名稱空間下已經封裝了FTP的幾個類,可以直接使用,非常方面,但是考慮到客戶端對.net的兼容問題,我還是覺得采用1.1的比較好,雖然費事,但也靈活。

 

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Net.Sockets;
using System.IO;
 
namespace FTPUpLoad
{
     ///<summary>
     /// Main 的摘要說明。
     ///
     ///存在的問題
     ///1.中文文件名 √
     ///2.文件分批讀取 √
     ///3.進度顯示
     ///4.擴展到控件中
     ///</summary>
     public class MainForm : System.Windows.Forms.Form
     {
         private System.Windows.Forms.TextBox msg;
         private System.Windows.Forms.Button commBtn;
         private System.Windows.Forms.Button pathBtn;
         private System.Windows.Forms.OpenFileDialog openPath;
         private System.Windows.Forms.TextBox path;
 
         private TcpClient tcp;
         private NetworkStream ns;
         private System.Windows.Forms.Label process;
 
         ///<summary>
         ///必需的設計器變量。
         ///</summary>
         private System.ComponentModel.Container components = null;
 
         public MainForm()
         {
              //
              // Windows 窗體設計器支持所必需的
              //
              InitializeComponent();
 
              //
              // TODO: 在 InitializeComponent 調用後添加任何構造函數代碼
              //
         }
 
         ///<summary>
         ///清理所有正在使用的資源。
         ///</summary>
         protected override void Dispose( bool disposing )
         {
              if( disposing )
              {
                   if(components != null)
                   {
                       components.Dispose();
                   }
              }
              base.Dispose( disposing );
         }
        
         ///<summary>
         ///應用程序的主入口點。
         ///</summary>
         [STAThread]
         static void Main()
         {
              Application.Run(new MainForm());
         }
 
         #region Windows 窗體設計器生成的代碼
         ///<summary>
         ///設計器支持所需的方法 - 不要使用代碼編輯器修改
         ///此方法的內容。
         ///</summary>
         private void InitializeComponent()
         {
              this.msg = new System.Windows.Forms.TextBox();
              this.path = new System.Windows.Forms.TextBox();
              this.commBtn = new System.Windows.Forms.Button();
              this.pathBtn = new System.Windows.Forms.Button();
              this.openPath = new System.Windows.Forms.OpenFileDialog();
              this.process = new System.Windows.Forms.Label();
              this.SuspendLayout();
              //
              // msg
              //
              this.msg.Location = new System.Drawing.Point(8, 152);
              this.msg.Multiline = true;
              this.msg.Name = "msg";
              this.msg.Size = new System.Drawing.Size(552, 192);
              this.msg.TabIndex = 3;
              this.msg.Text = "";
              //
              // path
              //
              this.path.Location = new System.Drawing.Point(8, 8);
              this.path.Name = "path";
              this.path.Size = new System.Drawing.Size(440, 21);
              this.path.TabIndex = 4;
              this.path.Text = "";
              //
              // commBtn
              //
              this.commBtn.Location = new System.Drawing.Point(232, 48);
              this.commBtn.Name = "commBtn";
              this.commBtn.TabIndex = 5;
              this.commBtn.Text = "Post";
              this.commBtn.Click += new System.EventHandler(this.commBtn_Click);
              //
              // pathBtn
              //
              this.pathBtn.Location = new System.Drawing.Point(464, 8);
              this.pathBtn.Name = "pathBtn";
              this.pathBtn.TabIndex = 6;
              this.pathBtn.Text = "瀏覽…";
              this.pathBtn.Click += new System.EventHandler(this.pathBtn_Click);
              //
              // openPath
              //
              this.openPath.FileOk += new System.ComponentModel.CancelEventHandler(this.openPath_FileOk);
              //
              // process
              //
              this.process.Location = new System.Drawing.Point(176, 112);
              this.process.Name = "process";
              this.process.Size = new System.Drawing.Size(248, 23);
              this.process.TabIndex = 7;
              //
              // MainForm
              //
              this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
              this.ClientSize = new System.Drawing.Size(568, 358);
              this.Controls.Add(this.process);
              this.Controls.Add(this.pathBtn);
              this.Controls.Add(this.commBtn);
              this.Controls.Add(this.path);
              this.Controls.Add(this.msg);
              this.Name = "MainForm";
              this.Text = "Main";
              this.Load += new System.EventHandler(this.MainForm_Load);
              this.ResumeLayout(false);
 
         }
         #endregion
        
         private void MainForm_Load(object sender, System.EventArgs e)
         {
             
              tcp = new TcpClient("192.168.1.88",21);
             
 
              //輸入用戶名
              WriteNetworkStream(ref ns,"USER Anonymous");
 
              msg.Text += ReadNetworkStream(ref ns);
 
              //輸入密碼
              WriteNetworkStream(ref ns,"PASS ");
 
              msg.Text += ReadNetworkStream(ref ns);
         }
 
         private void pathBtn_Click(object sender, System.EventArgs e)
         {
              openPath.ShowDialog();
         }
 
         private void openPath_FileOk(object sender, System.ComponentModel.CancelEventArgs e)
         {
              path.Text = openPath.FileName;
         }
 
         private void commBtn_Click(object sender, System.EventArgs e)
         {
 
              //刷新服務器當前目錄
              WriteNetworkStream(ref ns,"CWD /");
 
              msg.Text+=ReadNetworkStream(ref ns);
             
              //命令服務器數據模式爲被動模式
              WriteNetworkStream(ref ns,"PASV");
 
 
              //獲取服務器PASV被動模式打開的數據連接的IP和端口信息
              string str = ReadNetworkStream(ref ns);
 
              msg.Text+=str;
 
 
              //請求上傳文件,此處將命令轉換爲中文編碼的字節數組以支持中文文件名
              WriteNetworkStreamChs(ref ns,"STOR "+FileName(path.Text.Trim()));
 
              //組合IP和端口
              str =str.Substring(str.IndexOf("(")+1,str.IndexOf(")")-str.IndexOf("(")-1);
 
              string ip = str.Split(',')[0]+"."+str.Split(',')[1]+"."+str.Split(',')[2]+"."+str.Split(',')[3];
             
              int port = int.Parse(str.Split(',')[4])*256+int.Parse(str.Split(',')[5]);
 
 
              //獲取文件流
              FileStream fs = File.OpenRead(path.Text.Trim());
 
              //定義一個8字節數組做爲緩衝區
              byte[] b = new byte[8];
 
              //建立數據傳輸的TCP連接
              TcpClient tcp2 = new TcpClient(ip,port);
             
              //建立該連接的網絡流
              NetworkStream ns2 = tcp2.GetStream();
             
              //每8字節讀取文件流中數據到網絡流中,並寫入到基礎存儲設備,採用這個方式避免了由於一次性讀取大數據量到內存中造成客戶機內存使用過量。
              while(fs.Read(b,0,b.Length)>0)
              {
                   //建立數據的TCP連接並將文件流的內容寫入到網絡流
                   ns2.Write(b,0,b.Length);   
        
                   ns2.Flush();
 
              }
 
             
             
              //關閉所用的連接
              fs.Close();
 
              ns2.Close();
 
              tcp2.Close();
                         
 
              msg.Text += ReadNetworkStream(ref ns);
              msg.Text += ReadNetworkStream(ref ns);
 
             
         }
 
         #region //功能函數和方法
        
         ///<summary>
         /// ASCII編碼的命令請求
         ///</summary>
         ///<param name="ns">命令傳輸網絡流</param>
         ///<param name="comm">命令字符串</param>
         ///<returns></returns>
         protected string WriteNetworkStream(ref NetworkStream ns,string comm)
         {
 
              ns = tcp.GetStream();
 
              byte[] b = new byte[1024];
 
              b = System.Text.Encoding.ASCII.GetBytes(comm+"/r/n");
 
              ns.Write(b,0,b.Length);
 
              ns.Flush();
 
              return string.Empty;
         }
 
         ///<summary>
         ///中文編碼方式的命令請求
         ///</summary>
         ///<param name="ns">命令傳輸網絡流</param>
         ///<param name="comm">命令字符串</param>
         ///<returns></returns>
         protected string WriteNetworkStreamChs(ref NetworkStream ns,string comm)
         {
              ns = tcp.GetStream();
 
              byte[] b = new byte[1024];
 
              //將命令以中文編碼,以支持中文命令參數
              b = System.Text.Encoding.GetEncoding("GB2312").GetBytes(comm+"/r/n");
 
              ns.Write(b,0,b.Length);
 
              ns.Flush();
 
              return string.Empty;
         }
 
         ///<summary>
         ///獲取服務器相應字符串
         ///</summary>
         ///<param name="ns">命令傳輸網絡流</param>
         ///<returns>服務器相應字符串</returns>
         protected string ReadNetworkStream(ref NetworkStream ns)
         {
 
              ns = tcp.GetStream();
 
              byte[] b = new byte[1024];
 
              ns.Read(b,0,b.Length);
 
              ns.Flush();
 
              return System.Text.Encoding.ASCII.GetString(b);
         }
 
         ///<summary>
         ///獲取所選文件路徑的文件名
         ///</summary>
         ///<param name="path">文件路徑</param>
         ///<returns>文件名</returns>
         protected string FileName(string path)
         {
              return path.Substring(path.LastIndexOf("//")+1);
         }
 
         #endregion
 
        
     }
}
 
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章