falldog 发表于 2015-5-27 10:30:41

【转】WINFORM下FTP客户端的实现

  第一种方法:
  using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
  namespace Scan
{
    class FtpUpLoadFiles
    { ///   
      ///   FTPClient   的摘要说明。
      ///   
      public class FTPClient
      {
            #region   构造函数
            ///   
            ///   缺省构造函数
            ///   
            public FTPClient()
            {
                strRemoteHost = " ";
                strRemotePath = " ";
                strRemoteUser = " ";
                strRemotePass = " ";
                strRemotePort = 21;
                bConnected = false;
            }
  ///   
            ///   构造函数
            ///   
            ///   远程主机名
            ///   远程文件路径
            ///   登录服务器用户名
            ///   登录服务器密码
            ///   登录服务器端口号
            public FTPClient(string remoteHost, string remotePath, string remoteUser, string remotePass, int remotePort)
            {
                strRemoteHost = remoteHost;
                strRemotePath = remotePath;
                strRemoteUser = remoteUser;
                strRemotePass = remotePass;
                strRemotePort = remotePort;
                Connect();
            }
            #endregion
  
            #region   登陆属性
            ///   
            ///   FTP服务器IP地址
            ///   
            private string strRemoteHost;
  public string RemoteHost
            {
                get
                {
                  return strRemoteHost;
                }
                set
                {
                  strRemoteHost = value;
                }
            }
            ///   
            ///   FTP服务器端口
            ///   
            private int strRemotePort;
            public int RemotePort
            {
                get
                {
                  return strRemotePort;
                }
                set
                {
                  strRemotePort = value;
                }
            }
            ///   
            ///   当前服务器目录
            ///   
            private string strRemotePath;
            public string RemotePath
            {
                get
                {
                  return strRemotePath;
                }
                set
                {
                  strRemotePath = value;
                }
            }
            ///   
            ///   登录用户账号
            ///   
            private string strRemoteUser;
            public string RemoteUser
            {
                set
                {
                  strRemoteUser = value;
                }
            }
            ///   
            ///   用户登录密码
            ///   
            private string strRemotePass;
            public string RemotePass
            {
                set
                {
                  strRemotePass = value;
                }
            }   ///   
            ///   是否登录
            ///   
            private Boolean bConnected;
  public bool Connected
            {
                get
                {
                  return bConnected;
                }
            }
            #endregion
  
            #region   连接
            ///   
            ///   建立连接   
            ///   
            public void Connect()
            {
                Socket socketControl = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPEndPoint ep = new IPEndPoint(IPAddress.Parse(RemoteHost), strRemotePort);
                //   连接   
                try
                {
                  socketControl.Connect(ep);
                }
                catch (Exception)
                {
                  throw new IOException("不能连接到远程服务器!");
                }
                //   获取应答码
                ReadReply();
                if (iReplyCode != 220)
                {
                  DisConnect();
                  throw new IOException(strReply.Substring(4));
                }
                //   登陆
                SendCommand("USER   " + strRemoteUser);
                if (!(iReplyCode == 331 || iReplyCode == 230))
                {
                  CloseSocketConnect();//关闭连接
                  throw new IOException(strReply.Substring(4));
                }
                if (iReplyCode != 230)
                {
                  SendCommand("PASS   " + strRemotePass);
                  if (!(iReplyCode == 230 || iReplyCode == 202))
                  {
                        CloseSocketConnect();//关闭连接
                        throw new IOException(strReply.Substring(4));
                  }
                }
                bConnected = true;
                //   切换到目录
                ChDir(strRemotePath);
            }
            ///   
            ///   关闭连接
            ///   
            public void DisConnect()
            {
                if (socketControl != null)
                {
                  SendCommand("QUIT ");
                }
                CloseSocketConnect();
            }
            #endregion
  
            #region   传输模式
            ///   
            ///   传输模式:二进制类型、ASCII类型
            ///   
            public enum TransferType { Binary, ASCII };
            ///   
            ///   设置传输模式
            ///   
            ///    传输模式
            public void SetTransferType(TransferType ttType)
            {
                if (ttType == TransferType.Binary)
                {
                  SendCommand("TYPE   I ");//binary类型传输
                }
                else
                {
                  SendCommand("TYPE   A ");//ASCII类型传输
                }
                if (iReplyCode != 200)
                {
                  throw new IOException(strReply.Substring(4));
                }
                else
                {
                  trType = ttType;
                }
            }
            ///   
            ///   获得传输模式
            ///   
            ///    传输模式
            public TransferType GetTransferType()
            {
                return trType;
            }
  #endregion
            #region   上传和下载
            ///   
            ///   下载一批文件
            ///   
            ///    文件名的匹配字符串
            ///    本地目录(不得以\结束)
            ///    返回true成功
            public bool Get(string strFileNameMask, string strFolder)
            {
                try
                {
                  if (!bConnected)
                  {
                        Connect();
                  }
                  string[] strFiles = Dir(strFileNameMask);
                  foreach (string strFile in strFiles)
                  {
                        if (!strFile.Equals(" "))//一般来说strFiles的最后一个元素可能是空字符串
                        {
                            if (!Get(strFile, strFolder, strFile)) return false;
                        }
                  }
                  return true;
                }
                catch { return false; }
            }
  
            ///   
            ///   下载一个文件
            ///   
            ///    要下载的文件名
            ///    本地目录(不得以\结束)
            ///    保存在本地时的文件名
            ///    返回true成功
            public bool Get(string strRemoteFileName, string strFolder, string strLocalFileName)
            {
                try
                {
                  if (!bConnected)
                  {
                        Connect();
                  }
                  long fsSize = 0;
                  FileStream fs;
                  SetTransferType(TransferType.Binary);
                  if (strLocalFileName.Equals(" "))
                  {
                        strLocalFileName = strRemoteFileName;
                  }
  if (File.Exists(strFolder + "\\ " + strLocalFileName))
                  {
                        fs = File.OpenWrite(strFolder + "\\ " + strLocalFileName);
                        fsSize = fs.Length;
                        fs.Seek(fsSize, SeekOrigin.Current);
                  }
                  else
                  {
                        fs = new FileStream(strFolder + "\\ " + strLocalFileName, FileMode.Create);
                        fsSize = 0;
                  }
  
                  Socket socketData = CreateDataSocket();
                  SendCommand("RETR   " + strRemoteFileName);
  //125数据连接已打开,准备传送         
                  //150文件状态良好,打开数据连接`
                  //226关闭数据连接,请求的文件x作成功
                  //250请求的文件x作完成
                  if (!(iReplyCode == 150 || iReplyCode == 125
                      || iReplyCode == 226 || iReplyCode == 250))
                  {
                        throw new IOException(strReply.Substring(4));
                  }
  while (true)
                  {
                        int iBytes = socketData.Receive(buffer, buffer.Length, 0);
                        fs.Write(buffer, 0, iBytes);
                        if (iBytes0)
                  {
                        socketData.Send(buffer, iBytes, 0);
                  }
                  input.Close();
                  if (socketData.Connected)
                  {
                        socketData.Close();
                  }
                  //226关闭数据连接,请求的文件x作成功
                  //250请求的文件x作完成
                  if (!(iReplyCode == 226 || iReplyCode == 250))
                  {
                        ReadReply();
                        if (!(iReplyCode == 226 || iReplyCode == 250))
                        {
                            throw new IOException(strReply.Substring(4));
                        }
                  }
                  return true;
                }
                catch { return false; }
            }
  #endregion
             #region   内部变量
                ///   
                ///   服务器返回的应答信息(包含应答码)
                ///   
                private   string   strMsg;
                ///   
                ///   服务器返回的应答信息(包含应答码)
                ///   
                private   string   strReply;
                ///   
                ///   服务器返回的应答码
                ///   
                private   int   iReplyCode;
                ///   
                ///   进行控制连接的socket
                ///   
                private   Socket   socketControl;
                ///   
                ///   传输模式
                ///   
                private   TransferType   trType;
                ///   
                ///   接收和发送数据的缓冲区
                ///   
                private   static   int   BLOCK_SIZE   =   512;
                byte[]   buffer   =   new   byte;
                ///   
                ///   编码方式
                ///   
                Encoding   ASCII   =   Encoding.ASCII;
                #endregion
  
                #region   内部函数
                ///   
                ///   将一行应答字符串记录在strReply和strMsg
                ///   应答码记录在iReplyCode
                ///   
                private   void   ReadReply()
                {
                        strMsg   =   " ";
                        strReply   =   ReadLine();
                        iReplyCode   =   Int32.Parse(strReply.Substring(0,   3));
                }
  
                ///   
                ///   建立进行数据连接的socket
                ///   
                ///    数据连接socket
                private   Socket   CreateDataSocket()
                {
                        SendCommand( "PASV ");
                        if   (iReplyCode   !=   227)
                        {
                              throw   new   IOException(strReply.Substring(4));
                        }
                        int   index1   =   strReply.IndexOf( '(');
                        int   index2   =   strReply.IndexOf( ')');
                        string   ipData   =
                        strReply.Substring(index1   +   1,   index2   -   index1   -   1);
                        int[]   parts   =   new   int;
                        int   len   =   ipData.Length;
                        int   partCount   =   0;
                        string   buf   =   " ";
                        for   (int   i   =   0;   i   <   len   &&   partCount    0)
{
outputStream.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
}
ftpStream.Close();
outputStream.Close();
response.Close();
return 0;
}
catch (Exception ex)
{
Logging.WriteError(ex.Message + ex.StackTrace);
return -2;
}
}
页: [1]
查看完整版本: 【转】WINFORM下FTP客户端的实现