欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

分享用于操作FTP的客户端C#类

程序员文章站 2022-05-26 15:17:21
这是一个用于操作ftp的客户端c#类,类已经封装好了各种常用的ftp操作方法,调用非常简单,你不需要关心ftp连接和操作的细节,只要调用这个类里的相关方法就可以了。...

这是一个用于操作ftp的客户端c#类,类已经封装好了各种常用的ftp操作方法,调用非常简单,你不需要关心ftp连接和操作的细节,只要调用这个类里的相关方法就可以了。

using system;
using system.net;
using system.io;
using system.text;
using system.net.sockets;
using system.threading;
 
namespace dotnet.utilities
{
  public class ftpclient
  {
    public static object obj = new object();
 
    #region 构造函数
    /// <summary>
    /// 缺省构造函数
    /// </summary>
    public ftpclient()
    {
      strremotehost = "";
      strremotepath = "";
      strremoteuser = "";
      strremotepass = "";
      strremoteport = 21;
      bconnected = false;
    }
 
    /// <summary>
    /// 构造函数
    /// </summary>
    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 字段
    private int strremoteport;
    private boolean bconnected;
    private string strremotehost;
    private string strremotepass;
    private string strremoteuser;
    private string strremotepath;
 
    /// <summary>
    /// 服务器返回的应答信息(包含应答码)
    /// </summary>
    private string strmsg;
    /// <summary>
    /// 服务器返回的应答信息(包含应答码)
    /// </summary>
    private string strreply;
    /// <summary>
    /// 服务器返回的应答码
    /// </summary>
    private int ireplycode;
    /// <summary>
    /// 进行控制连接的socket
    /// </summary>
    private socket socketcontrol;
    /// <summary>
    /// 传输模式
    /// </summary>
    private transfertype trtype;
    /// <summary>
    /// 接收和发送数据的缓冲区
    /// </summary>
    private static int block_size = 512;
    /// <summary>
    /// 编码方式
    /// </summary>
    encoding ascii = encoding.ascii;
    /// <summary>
    /// 字节数组
    /// </summary>
    byte[] buffer = new byte[block_size];
    #endregion
 
    #region 属性
    /// <summary>
    /// ftp服务器ip地址
    /// </summary>
    public string remotehost
    {
      get
      {
        return strremotehost;
      }
      set
      {
        strremotehost = value;
      }
    }
 
    /// <summary>
    /// ftp服务器端口
    /// </summary>
    public int remoteport
    {
      get
      {
        return strremoteport;
      }
      set
      {
        strremoteport = value;
      }
    }
 
    /// <summary>
    /// 当前服务器目录
    /// </summary>
    public string remotepath
    {
      get
      {
        return strremotepath;
      }
      set
      {
        strremotepath = value;
      }
    }
 
    /// <summary>
    /// 登录用户账号
    /// </summary>
    public string remoteuser
    {
      set
      {
        strremoteuser = value;
      }
    }
 
    /// <summary>
    /// 用户登录密码
    /// </summary>
    public string remotepass
    {
      set
      {
        strremotepass = value;
      }
    }
 
    /// <summary>
    /// 是否登录
    /// </summary>
    public bool connected
    {
      get
      {
        return bconnected;
      }
    }
    #endregion
 
    #region 链接
    /// <summary>
    /// 建立连接
    /// </summary>
    public void connect()
    {
      lock (obj)
      {
        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("不能连接ftp服务器");
        }
      }
      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);
    }
 
    /// <summary>
    /// 关闭连接
    /// </summary>
    public void disconnect()
    {
      if (socketcontrol != null)
      {
        sendcommand("quit");
      }
      closesocketconnect();
    }
    #endregion
 
    #region 传输模式
    /// <summary>
    /// 传输模式:二进制类型、ascii类型
    /// </summary>
    public enum transfertype { binary, ascii };
 
    /// <summary>
    /// 设置传输模式
    /// </summary>
    /// <param name="tttype">传输模式</param>
    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;
      }
    }
 
    /// <summary>
    /// 获得传输模式
    /// </summary>
    /// <returns>传输模式</returns>
    public transfertype gettransfertype()
    {
      return trtype;
    }
    #endregion
 
    #region 文件操作
    /// <summary>
    /// 获得文件列表
    /// </summary>
    /// <param name="strmask">文件名的匹配字符串</param>
    public string[] dir(string strmask)
    {
      if (!bconnected)
      {
        connect();
      }
      socket socketdata = createdatasocket();
      sendcommand("nlst " + strmask);
      if (!(ireplycode == 150 || ireplycode == 125 || ireplycode == 226))
      {
        throw new ioexception(strreply.substring(4));
      }
      strmsg = "";
      thread.sleep(2000);
      while (true)
      {
        int ibytes = socketdata.receive(buffer, buffer.length, 0);
        strmsg += ascii.getstring(buffer, 0, ibytes);
        if (ibytes < buffer.length)
        {
          break;
        }
      }
      char[] seperator = { '\n' };
      string[] strsfilelist = strmsg.split(seperator);
      socketdata.close(); //数据socket关闭时也会有返回码
      if (ireplycode != 226)
      {
        readreply();
        if (ireplycode != 226)
        {
 
          throw new ioexception(strreply.substring(4));
        }
      }
      return strsfilelist;
    }
 
    public void newputbyguid(string strfilename, string strguid)
    {
      if (!bconnected)
      {
        connect();
      }
      string str = strfilename.substring(0, strfilename.lastindexof("\\"));
      string strtypename = strfilename.substring(strfilename.lastindexof("."));
      strguid = str + "\\" + strguid;
      socket socketdata = createdatasocket();
      sendcommand("stor " + path.getfilename(strguid));
      if (!(ireplycode == 125 || ireplycode == 150))
      {
        throw new ioexception(strreply.substring(4));
      }
      filestream input = new filestream(strguid, filemode.open);
      input.flush();
      int ibytes = 0;
      while ((ibytes = input.read(buffer, 0, buffer.length)) > 0)
      {
        socketdata.send(buffer, ibytes, 0);
      }
      input.close();
      if (socketdata.connected)
      {
        socketdata.close();
      }
      if (!(ireplycode == 226 || ireplycode == 250))
      {
        readreply();
        if (!(ireplycode == 226 || ireplycode == 250))
        {
          throw new ioexception(strreply.substring(4));
        }
      }
    }
 
    /// <summary>
    /// 获取文件大小
    /// </summary>
    /// <param name="strfilename">文件名</param>
    /// <returns>文件大小</returns>
    public long getfilesize(string strfilename)
    {
      if (!bconnected)
      {
        connect();
      }
      sendcommand("size " + path.getfilename(strfilename));
      long lsize = 0;
      if (ireplycode == 213)
      {
        lsize = int64.parse(strreply.substring(4));
      }
      else
      {
        throw new ioexception(strreply.substring(4));
      }
      return lsize;
    }
 
 
    /// <summary>
    /// 获取文件信息
    /// </summary>
    /// <param name="strfilename">文件名</param>
    /// <returns>文件大小</returns>
    public string getfileinfo(string strfilename)
    {
      if (!bconnected)
      {
        connect();
      }
      socket socketdata = createdatasocket();
      sendcommand("list " + strfilename);
      string strresult = "";
      if (!(ireplycode == 150 || ireplycode == 125
        || ireplycode == 226 || ireplycode == 250))
      {
        throw new ioexception(strreply.substring(4));
      }
      byte[] b = new byte[512];
      memorystream ms = new memorystream();
 
      while (true)
      {
        int ibytes = socketdata.receive(b, b.length, 0);
        ms.write(b, 0, ibytes);
        if (ibytes <= 0)
        {
 
          break;
        }
      }
      byte[] bt = ms.getbuffer();
      strresult = system.text.encoding.ascii.getstring(bt);
      ms.close();
      return strresult;
    }
 
    /// <summary>
    /// 删除
    /// </summary>
    /// <param name="strfilename">待删除文件名</param>
    public void delete(string strfilename)
    {
      if (!bconnected)
      {
        connect();
      }
      sendcommand("dele " + strfilename);
      if (ireplycode != 250)
      {
        throw new ioexception(strreply.substring(4));
      }
    }
 
    /// <summary>
    /// 重命名(如果新文件名与已有文件重名,将覆盖已有文件)
    /// </summary>
    /// <param name="stroldfilename">旧文件名</param>
    /// <param name="strnewfilename">新文件名</param>
    public void rename(string stroldfilename, string strnewfilename)
    {
      if (!bconnected)
      {
        connect();
      }
      sendcommand("rnfr " + stroldfilename);
      if (ireplycode != 350)
      {
        throw new ioexception(strreply.substring(4));
      }
      // 如果新文件名与原有文件重名,将覆盖原有文件
      sendcommand("rnto " + strnewfilename);
      if (ireplycode != 250)
      {
        throw new ioexception(strreply.substring(4));
      }
    }
    #endregion
 
    #region 上传和下载
    /// <summary>
    /// 下载一批文件
    /// </summary>
    /// <param name="strfilenamemask">文件名的匹配字符串</param>
    /// <param name="strfolder">本地目录(不得以\结束)</param>
    public void get(string strfilenamemask, string strfolder)
    {
      if (!bconnected)
      {
        connect();
      }
      string[] strfiles = dir(strfilenamemask);
      foreach (string strfile in strfiles)
      {
        if (!strfile.equals(""))//一般来说strfiles的最后一个元素可能是空字符串
        {
          get(strfile, strfolder, strfile);
        }
      }
    }
 
    /// <summary>
    /// 下载一个文件
    /// </summary>
    /// <param name="strremotefilename">要下载的文件名</param>
    /// <param name="strfolder">本地目录(不得以\结束)</param>
    /// <param name="strlocalfilename">保存在本地时的文件名</param>
    public void get(string strremotefilename, string strfolder, string strlocalfilename)
    {
      socket socketdata = createdatasocket();
      try
      {
        if (!bconnected)
        {
          connect();
        }
        settransfertype(transfertype.binary);
        if (strlocalfilename.equals(""))
        {
          strlocalfilename = strremotefilename;
        }
        sendcommand("retr " + strremotefilename);
        if (!(ireplycode == 150 || ireplycode == 125 || ireplycode == 226 || ireplycode == 250))
        {
          throw new ioexception(strreply.substring(4));
        }
        filestream output = new filestream(strfolder + "\\" + strlocalfilename, filemode.create);
        while (true)
        {
          int ibytes = socketdata.receive(buffer, buffer.length, 0);
          output.write(buffer, 0, ibytes);
          if (ibytes <= 0)
          {
            break;
          }
        }
        output.close();
        if (socketdata.connected)
        {
          socketdata.close();
        }
        if (!(ireplycode == 226 || ireplycode == 250))
        {
          readreply();
          if (!(ireplycode == 226 || ireplycode == 250))
          {
            throw new ioexception(strreply.substring(4));
          }
        }
      }
      catch
      {
        socketdata.close();
        socketdata = null;
        socketcontrol.close();
        bconnected = false;
        socketcontrol = null;
      }
    }
 
    /// <summary>
    /// 下载一个文件
    /// </summary>
    /// <param name="strremotefilename">要下载的文件名</param>
    /// <param name="strfolder">本地目录(不得以\结束)</param>
    /// <param name="strlocalfilename">保存在本地时的文件名</param>
    public void getnobinary(string strremotefilename, string strfolder, string strlocalfilename)
    {
      if (!bconnected)
      {
        connect();
      }
 
      if (strlocalfilename.equals(""))
      {
        strlocalfilename = strremotefilename;
      }
      socket socketdata = createdatasocket();
      sendcommand("retr " + strremotefilename);
      if (!(ireplycode == 150 || ireplycode == 125 || ireplycode == 226 || ireplycode == 250))
      {
        throw new ioexception(strreply.substring(4));
      }
      filestream output = new filestream(strfolder + "\\" + strlocalfilename, filemode.create);
      while (true)
      {
        int ibytes = socketdata.receive(buffer, buffer.length, 0);
        output.write(buffer, 0, ibytes);
        if (ibytes <= 0)
        {
          break;
        }
      }
      output.close();
      if (socketdata.connected)
      {
        socketdata.close();
      }
      if (!(ireplycode == 226 || ireplycode == 250))
      {
        readreply();
        if (!(ireplycode == 226 || ireplycode == 250))
        {
          throw new ioexception(strreply.substring(4));
        }
      }
    }
 
    /// <summary>
    /// 上传一批文件
    /// </summary>
    /// <param name="strfolder">本地目录(不得以\结束)</param>
    /// <param name="strfilenamemask">文件名匹配字符(可以包含*和?)</param>
    public void put(string strfolder, string strfilenamemask)
    {
      string[] strfiles = directory.getfiles(strfolder, strfilenamemask);
      foreach (string strfile in strfiles)
      {
        put(strfile);
      }
    }
 
    /// <summary>
    /// 上传一个文件
    /// </summary>
    /// <param name="strfilename">本地文件名</param>
    public void put(string strfilename)
    {
      if (!bconnected)
      {
        connect();
      }
      socket socketdata = createdatasocket();
      if (path.getextension(strfilename) == "")
        sendcommand("stor " + path.getfilenamewithoutextension(strfilename));
      else
        sendcommand("stor " + path.getfilename(strfilename));
 
      if (!(ireplycode == 125 || ireplycode == 150))
      {
        throw new ioexception(strreply.substring(4));
      }
 
      filestream input = new filestream(strfilename, filemode.open);
      int ibytes = 0;
      while ((ibytes = input.read(buffer, 0, buffer.length)) > 0)
      {
        socketdata.send(buffer, ibytes, 0);
      }
      input.close();
      if (socketdata.connected)
      {
        socketdata.close();
      }
      if (!(ireplycode == 226 || ireplycode == 250))
      {
        readreply();
        if (!(ireplycode == 226 || ireplycode == 250))
        {
          throw new ioexception(strreply.substring(4));
        }
      }
    }
 
 
    /// <summary>
    /// 上传一个文件
    /// </summary>
    /// <param name="strfilename">本地文件名</param>
    public void putbyguid(string strfilename, string strguid)
    {
      if (!bconnected)
      {
        connect();
      }
      string str = strfilename.substring(0, strfilename.lastindexof("\\"));
      string strtypename = strfilename.substring(strfilename.lastindexof("."));
      strguid = str + "\\" + strguid;
      system.io.file.copy(strfilename, strguid);
      system.io.file.setattributes(strguid, system.io.fileattributes.normal);
      socket socketdata = createdatasocket();
      sendcommand("stor " + path.getfilename(strguid));
      if (!(ireplycode == 125 || ireplycode == 150))
      {
        throw new ioexception(strreply.substring(4));
      }
      filestream input = new filestream(strguid, filemode.open, system.io.fileaccess.read, system.io.fileshare.read);
      int ibytes = 0;
      while ((ibytes = input.read(buffer, 0, buffer.length)) > 0)
      {
        socketdata.send(buffer, ibytes, 0);
      }
      input.close();
      file.delete(strguid);
      if (socketdata.connected)
      {
        socketdata.close();
      }
      if (!(ireplycode == 226 || ireplycode == 250))
      {
        readreply();
        if (!(ireplycode == 226 || ireplycode == 250))
        {
          throw new ioexception(strreply.substring(4));
        }
      }
    }
    #endregion
 
    #region 目录操作
    /// <summary>
    /// 创建目录
    /// </summary>
    /// <param name="strdirname">目录名</param>
    public void mkdir(string strdirname)
    {
      if (!bconnected)
      {
        connect();
      }
      sendcommand("mkd " + strdirname);
      if (ireplycode != 257)
      {
        throw new ioexception(strreply.substring(4));
      }
    }
 
    /// <summary>
    /// 删除目录
    /// </summary>
    /// <param name="strdirname">目录名</param>
    public void rmdir(string strdirname)
    {
      if (!bconnected)
      {
        connect();
      }
      sendcommand("rmd " + strdirname);
      if (ireplycode != 250)
      {
        throw new ioexception(strreply.substring(4));
      }
    }
 
    /// <summary>
    /// 改变目录
    /// </summary>
    /// <param name="strdirname">新的工作目录名</param>
    public void chdir(string strdirname)
    {
      if (strdirname.equals(".") || strdirname.equals(""))
      {
        return;
      }
      if (!bconnected)
      {
        connect();
      }
      sendcommand("cwd " + strdirname);
      if (ireplycode != 250)
      {
        throw new ioexception(strreply.substring(4));
      }
      this.strremotepath = strdirname;
    }
    #endregion
 
    #region 内部函数
    /// <summary>
    /// 将一行应答字符串记录在strreply和strmsg,应答码记录在ireplycode
    /// </summary>
    private void readreply()
    {
      strmsg = "";
      strreply = readline();
      ireplycode = int32.parse(strreply.substring(0, 3));
    }
 
    /// <summary>
    /// 建立进行数据连接的socket
    /// </summary>
    /// <returns>数据连接socket</returns>
    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[6];
      int len = ipdata.length;
      int partcount = 0;
      string buf = "";
      for (int i = 0; i < len && partcount <= 6; i++)
      {
        char ch = char.parse(ipdata.substring(i, 1));
        if (char.isdigit(ch))
          buf += ch;
        else if (ch != ',')
        {
          throw new ioexception("malformed pasv strreply: " + strreply);
        }
        if (ch == ',' || i + 1 == len)
        {
          try
          {
            parts[partcount++] = int32.parse(buf);
            buf = "";
          }
          catch (exception)
          {
            throw new ioexception("malformed pasv strreply: " + strreply);
          }
        }
      }
      string ipaddress = parts[0] + "." + parts[1] + "." + parts[2] + "." + parts[3];
      int port = (parts[4] << 8) + parts[5];
      socket s = new socket(addressfamily.internetwork, sockettype.stream, protocoltype.tcp);
      ipendpoint ep = new ipendpoint(ipaddress.parse(ipaddress), port);
      try
      {
        s.connect(ep);
      }
      catch (exception)
      {
        throw new ioexception("无法连接ftp服务器");
      }
      return s;
    }
 
    /// <summary>
    /// 关闭socket连接(用于登录以前)
    /// </summary>
    private void closesocketconnect()
    {
      lock (obj)
      {
        if (socketcontrol != null)
        {
          socketcontrol.close();
          socketcontrol = null;
        }
        bconnected = false;
      }
    }
 
    /// <summary>
    /// 读取socket返回的所有字符串
    /// </summary>
    /// <returns>包含应答码的字符串行</returns>
    private string readline()
    {
      lock (obj)
      {
        while (true)
        {
          int ibytes = socketcontrol.receive(buffer, buffer.length, 0);
          strmsg += ascii.getstring(buffer, 0, ibytes);
          if (ibytes < buffer.length)
          {
            break;
          }
        }
      }
      char[] seperator = { '\n' };
      string[] mess = strmsg.split(seperator);
      if (strmsg.length > 2)
      {
        strmsg = mess[mess.length - 2];
      }
      else
      {
        strmsg = mess[0];
      }
      if (!strmsg.substring(3, 1).equals(" ")) //返回字符串正确的是以应答码(如220开头,后面接一空格,再接问候字符串)
      {
        return readline();
      }
      return strmsg;
    }
 
    /// <summary>
    /// 发送命令并获取应答码和最后一行应答字符串
    /// </summary>
    /// <param name="strcommand">命令</param>
    public void sendcommand(string strcommand)
    {
      lock (obj)
      {
        byte[] cmdbytes = encoding.ascii.getbytes((strcommand + "\r\n").tochararray());
        socketcontrol.send(cmdbytes, cmdbytes.length, 0);
        thread.sleep(500);
        readreply();
      }
    }
    #endregion
  }
}

方法二:

using system;
using system.net;
using system.io;
using system.text;
using system.net.sockets;
namespace ftplib
{
public class ftpfactory
{
  private string
  remotehost, remotepath, remoteuser, remotepass, mes;
  private int remoteport, bytes;
  private socket clientsocket;
  private int retvalue;
  private boolean debug;
  private boolean logined;
  private string reply;
  private static int block_size = 512;
  byte[] buffer = new byte[block_size];
  encoding ascii = encoding.ascii;
  public ftpfactory()
  {
    remotehost = "localhost";
    remotepath = ".";
    remoteuser = "anonymous";
    remotepass = "";
    remoteport = 21;
    debug = false;
    logined = false;
  }
  ///

  /// set the name of the ftp server to connect to.

  ///

  /// server name

  public void setremotehost(string remotehost)
  {
    this.remotehost = remotehost;
  }
  ///

  /// return the name of the current ftp server.

  ///

  /// server name

  public string getremotehost()
  {
    return remotehost;
  }
  ///

  /// set the port number to use for ftp.

  ///

  /// port number

  public void setremoteport(int remoteport)
  {
    this.remoteport = remoteport;
  }
  ///

  /// return the current port number.

  ///

  /// current port number

  public int getremoteport()
  {
    return remoteport;
  }
  ///

  /// set the remote directory path.

  ///

  /// the remote directory path

  public void setremotepath(string remotepath)
  {
    this.remotepath = remotepath;
  }
  ///

  /// return the current remote directory path.

  ///

  /// the current remote directory path.

  public string getremotepath()
  {
    return remotepath;
  }
  ///

  /// set the user name to use for logging into the remote server.

  ///

  /// username

  public void setremoteuser(string remoteuser)
  {
    this.remoteuser = remoteuser;
  }
  ///

  /// set the password to user for logging into the remote server.

  ///

  /// password

  public void setremotepass(string remotepass)
  {
    this.remotepass = remotepass;
  }
  ///

  /// return a string array containing the remote directory's file list.

  ///

  ///

  ///

  public string[] getfilelist(string mask)
  {
    if (!logined)
    {
      login();
    }
    socket csocket = createdatasocket();
    sendcommand("nlst " + mask);
    if (!(retvalue == 150 || retvalue == 125))
    {
      throw new ioexception(reply.substring(4));
    }
    mes = "";
    while (true)
    {
      int bytes = csocket.receive(buffer, buffer.length, 0);
      mes += ascii.getstring(buffer, 0, bytes);
      if (bytes < buffer.length)
      {
        break;
      }
    }
    char[] seperator = { '\n' };
    string[] mess = mes.split(seperator);
    csocket.close();
    readreply();
    if (retvalue != 226)
    {
      throw new ioexception(reply.substring(4));
    }
    return mess;
  }
  ///

  /// return the size of a file.

  ///

  ///

  ///

  public long getfilesize(string filename)
  {
    if (!logined)
    {
      login();
    }
    sendcommand("size " + filename);
    long size = 0;
    if (retvalue == 213)
    {
      size = int64.parse(reply.substring(4));
    }
    else
    {
      throw new ioexception(reply.substring(4));
    }
    return size;
  }
  ///

  /// login to the remote server.

  ///

  public void login()
  {
    clientsocket = new
    socket(addressfamily.internetwork, sockettype.stream, protocoltype.tcp);
    ipendpoint ep = new
    ipendpoint(dns.resolve(remotehost).addresslist[0], remoteport);
    try
    {
      clientsocket.connect(ep);
    }
    catch (exception)
    {
      throw new ioexception("couldn't connect to remote server");
    }
    readreply();
    if (retvalue != 220)
    {
      close();
      throw new ioexception(reply.substring(4));
    }
    if (debug)
      console.writeline("user " + remoteuser);
    sendcommand("user " + remoteuser);
    if (!(retvalue == 331 || retvalue == 230))
    {
      cleanup();
      throw new ioexception(reply.substring(4));
    }
    if (retvalue != 230)
    {
      if (debug)
        console.writeline("pass xxx");
      sendcommand("pass " + remotepass);
      if (!(retvalue == 230 || retvalue == 202))
      {
        cleanup();
        throw new ioexception(reply.substring(4));
      }
    }
    logined = true;
    console.writeline("connected to " + remotehost);
    chdir(remotepath);
  }
  ///

  /// if the value of mode is true, set binary mode for downloads.

  /// else, set ascii mode.

  ///

  ///

  public void setbinarymode(boolean mode)
  {
    if (mode)
    {
      sendcommand("type i");
    }
    else
    {
      sendcommand("type a");
    }
    if (retvalue != 200)
    {
      throw new ioexception(reply.substring(4));
    }
  }
  ///

  /// download a file to the assembly's local directory,

  /// keeping the same file name.

  ///

  ///

  public void download(string remfilename)
  {
    download(remfilename, "", false);
  }
  ///

  /// download a remote file to the assembly's local directory,

  /// keeping the same file name, and set the resume flag.

  ///

  ///

  ///

  public void download(string remfilename, boolean resume)
  {
    download(remfilename, "", resume);
  }
  ///

  /// download a remote file to a local file name which can include

  /// a path. the local file name will be created or overwritten,

  /// but the path must exist.

  ///

  ///

  ///

  public void download(string remfilename, string locfilename)
  {
    download(remfilename, locfilename, false);
  }
  ///

  /// download a remote file to a local file name which can include

  /// a path, and set the resume flag. the local file name will be

  /// created or overwritten, but the path must exist.

  ///

  ///

  ///

  ///

  public void download(string remfilename, string
  locfilename, boolean resume)
  {
    if (!logined)
    {
      login();
    }
    setbinarymode(true);
    console.writeline("downloading file " + remfilename + " from " + remotehost + "/" + remotepath);
    if (locfilename.equals(""))
    {
      locfilename = remfilename;
    }
    if (!file.exists(locfilename))
    {
      stream st = file.create(locfilename);
      st.close();
    }
    filestream output = new
    filestream(locfilename, filemode.open);
    socket csocket = createdatasocket();
    long offset = 0;
    if (resume)
    {
      offset = output.length;
      if (offset > 0)
      {
        sendcommand("rest " + offset);
        if (retvalue != 350)
        {
          //throw new ioexception(reply.substring(4));

          //some servers may not support resuming.

          offset = 0;
        }
      }
      if (offset > 0)
      {
        if (debug)
        {
          console.writeline("seeking to " + offset);
        }
        long npos = output.seek(offset, seekorigin.begin);
        console.writeline("new pos=" + npos);
      }
    }
    sendcommand("retr " + remfilename);
    if (!(retvalue == 150 || retvalue == 125) )
    {
      throw new ioexception(reply.substring(4));
    }
    while (true)
    {
      bytes = csocket.receive(buffer, buffer.length, 0);
      output.write(buffer, 0, bytes);
      if (bytes <= 0)
      {
        break;
      }
    }
    output.close();
    if (csocket.connected)
    {
      csocket.close();
    }
    console.writeline("");
    readreply();
    if (!(retvalue == 226 || retvalue == 250))
    {
      throw new ioexception(reply.substring(4));
    }
  }
  ///

  /// upload a file.

  ///

  ///

  public void upload(string filename)
  {
    upload(filename, false);
  }
  ///

  /// upload a file and set the resume flag.

  ///

  ///

  ///

  public void upload(string filename, boolean resume)
  {
    if (!logined)
    {
      login();
    }
    socket csocket = createdatasocket();
    long offset = 0;
    if (resume)
    {
      try
      {
        setbinarymode(true);
        offset = getfilesize(filename);
      }
      catch (exception)
      {
        offset = 0;
      }
    }
    if (offset > 0)
    {
      sendcommand("rest " + offset);
      if (retvalue != 350)
      {
        //throw new ioexception(reply.substring(4));

        //remote server may not support resuming.

        offset = 0;
      }
    }
    sendcommand("stor " + path.getfilename(filename));
    if (!(retvalue == 125 || retvalue == 150))
    {
      throw new ioexception(reply.substring(4));
    }
    // open input stream to read source file

    filestream input = new
    filestream(filename, filemode.open);
    if (offset != 0)
    {
      if (debug)
      {
        console.writeline("seeking to " + offset);
      }
      input.seek(offset, seekorigin.begin);
    }
    console.writeline("uploading file " + filename + " to " + remotepath);
    while ((bytes = input.read(buffer, 0, buffer.length)) > 0)
    {
      csocket.send(buffer, bytes, 0);
    }
    input.close();
    console.writeline("");
    if (csocket.connected)
    {
      csocket.close();
    }
    readreply();
    if (!(retvalue == 226 || retvalue == 250))
    {
      throw new ioexception(reply.substring(4));
    }
  }
  ///

  /// delete a file from the remote ftp server.

  ///

  ///

  public void deleteremotefile(string filename)
  {
    if (!logined)
    {
      login();
    }
    sendcommand("dele " + filename);
    if (retvalue != 250)
    {
      throw new ioexception(reply.substring(4));
    }
  }
  ///

  /// rename a file on the remote ftp server.

  ///

  ///

  ///

  public void renameremotefile(string oldfilename, string
  newfilename)
  {
    if (!logined)
    {
      login();
    }
    sendcommand("rnfr " + oldfilename);
    if (retvalue != 350)
    {
      throw new ioexception(reply.substring(4));
    }
    // known problem

    // rnto will not take care of existing file.

    // i.e. it will overwrite if newfilename exist

    sendcommand("rnto " + newfilename);
    if (retvalue != 250)
    {
      throw new ioexception(reply.substring(4));
    }
  }
  ///

  /// create a directory on the remote ftp server.

  ///

  ///

  public void mkdir(string dirname)
  {
    if (!logined)
    {
      login();
    }
    sendcommand("mkd " + dirname);
    if (retvalue != 257)
    {
      throw new ioexception(reply.substring(4));
    }
  }
  ///

  /// delete a directory on the remote ftp server.

  ///

  ///

  public void rmdir(string dirname)
  {
    if (!logined)
    {
      login();
    }
    sendcommand("rmd " + dirname);
    if (retvalue != 250)
    {
      throw new ioexception(reply.substring(4));
    }
  }
  ///

  /// change the current working directory on the remote ftp server.

  ///

  ///

  public void chdir(string dirname)
  {
    if (dirname.equals("."))
    {
      return;
    }
    if (!logined)
    {
      login();
    }
    sendcommand("cwd " + dirname);
    if (retvalue != 250)
    {
      throw new ioexception(reply.substring(4));
    }
    this.remotepath = dirname;
    console.writeline("current directory is " + remotepath);
  }
  ///

  /// close the ftp connection.

  ///

  public void close()
  {
    if (clientsocket != null)
    {
      sendcommand("quit");
    }
    cleanup();
    console.writeline("closing...");
  }
  ///

  /// set debug mode.

  ///

  ///

  public void setdebug(boolean debug)
  {
    this.debug = debug;
  }
  private void readreply()
  {
    mes = "";
    reply = readline();
    retvalue = int32.parse(reply.substring(0, 3));
  }
  private void cleanup()
  {
    if (clientsocket != null)
    {
      clientsocket.close();
      clientsocket = null;
    }
    logined = false;
  }
  private string readline()
  {
    while (true)
    {
      bytes = clientsocket.receive(buffer, buffer.length, 0);
      mes += ascii.getstring(buffer, 0, bytes);
      if (bytes < buffer.length)
      {
        break;
      }
    }
    char[] seperator = { '\n' };
    string[] mess = mes.split(seperator);
    if (mes.length > 2)
    {
      mes = mess[mess.length - 2];
    }
    else
    {
      mes = mess[0];
    }
    if (!mes.substring(3, 1).equals(" "))
    {
      return readline();
    }
    if (debug)
    {
      for (int k = 0; k < mess.length - 1; k++)
      {
        console.writeline(mess[k]);
      }
    }
    return mes;
  }
  private void sendcommand(string command)
  {
    byte[] cmdbytes =
      //encoding.ascii.getbytes((command + "\r\n").tochararray());

    encoding.default.getbytes((command + "\r\n").tochararray()); 
    clientsocket.send(cmdbytes, cmdbytes.length, 0);
    readreply();
  }
  private socket createdatasocket()
  {
    sendcommand("pasv");
    if (retvalue != 227)
    {
      throw new ioexception(reply.substring(4));
    }
    int index1 = reply.indexof('(');
    int index2 = reply.indexof(')');
    string ipdata =
    reply.substring(index1 + 1, index2 - index1 - 1);
    int[] parts = new int[6];
    int len = ipdata.length;
    int partcount = 0;
    string buf = "";
    for (int i = 0; i < len && partcount <= 6; i++)
    {
      char ch = char.parse(ipdata.substring(i, 1));
      if (char.isdigit(ch))
        buf += ch;
      else if (ch != ',')
      {
        throw new ioexception("malformed pasv reply: " +
        reply);
      }
      if (ch == ',' || i + 1 == len)
      {
        try
        {
          parts[partcount++] = int32.parse(buf);
          buf = "";
        }
        catch (exception)
        {
          throw new ioexception("malformed pasv reply: " +
          reply);
        }
      }
    }
    string ipaddress = parts[0] + "." + parts[1] + "." +
    parts[2] + "." + parts[3];
    int port = (parts[4] << 8) + parts[5];
    socket s = new
    socket(addressfamily.internetwork, sockettype.stream, protocoltype.tcp);
    ipendpoint ep = new
    ipendpoint(dns.resolve(ipaddress).addresslist[0], port);
    try
    {
      s.connect(ep);
    }
    catch (exception)
    {
      throw new ioexception("can't connect to remote server");
    }
    return s;
  }
}
}

以上所述就是本文的全部内容了,希望大家能够喜欢。