当前位置: 代码网 > it编程>编程语言>C# > C#中FTP常用操作的示例代码

C#中FTP常用操作的示例代码

2024年05月26日 C# 我要评论
c# ftp常用操作直接上代码。以后有空在解释一下public class ftpstate { private manualresetevent wait; private ftpwe

c# ftp常用操作

直接上代码。以后有空在解释一下

public class ftpstate
  {
    private manualresetevent wait;
    private ftpwebrequest request;
    private string filename;
    private exception operationexception = null;
    string status;
 
    public ftpstate()
    {
      wait = new manualresetevent(false);
    }
 
    public manualresetevent operationcomplete
    {
      get { return wait; }
    }
 
    public ftpwebrequest request
    {
      get { return request; }
      set { request = value; }
    }
 
    public string filename
    {
      get { return filename; }
      set { filename = value; }
    }
    public exception operationexception
    {
      get { return operationexception; }
      set { operationexception = value; }
    }
    public string statusdescription
    {
      get { return status; }
      set { status = value; }
    }
  }
 
  //包含了对ftp常用的方法
  public class ftpclient
  {
    #region 构造函数
    /// <summary>
    /// 创建ftp工具
    /// <para>
    /// 默认不使用ssl,使用二进制传输方式,使用被动模式ftp有两种使用模式:主动和被动。
    /// 主动模式要求客户端和服务器端同时打开并且监听一个端口以建立连接。
    /// 在这种情况下,客户端由于安装了防火墙会产生一些问题。
    /// 所以,创立了被动模式。
    /// 被动模式只要求服务器端产生一个监听相应端口的进程,这样就可以绕过客户端安装了防火墙的问题。
    /// </para>
    /// </summary>
    /// <param name="host">主机名称</param>
    /// <param name="userid">用户名</param>
    /// <param name="password">密码</param>
    public ftpclient(string host, string userid, string password)
      : this(host, userid, password, 8022, null, false, true, true)
    {
        }
 
    /// <summary>
    /// 创建ftp工具
    /// </summary>
    /// <param name="host">主机名称</param>
    /// <param name="userid">用户名</param>
    /// <param name="password">密码</param>
    /// <param name="port">端口</param>
    /// <param name="enablessl">允许ssl</param>
    /// <param name="proxy">代理</param>
    /// <param name="usebinary">允许二进制</param>
    /// <param name="usepassive">允许被动模式</param>
    public ftpclient(string host, string userid, string password, int port, iwebproxy proxy, bool enablessl, bool usebinary, bool usepassive)
    {
            this.userid = userid;
            this.password = password;
            mesoperate dal = new mesoperate();
            datatable dt = dal.getserver();
            string ip = "";
            foreach (ipaddress _ipaddress in dns.gethostentry(dns.gethostname()).addresslist)
            {
                if (_ipaddress.addressfamily.tostring() == "internetwork")
                {
                    ip = _ipaddress.tostring();
                }
            }
            if (ip.substring(0, 6) == "172.30")
            {
                this.host = "ftp://" +dt.rows[0]["server_ip_new"].tostring();//产线
            }
            else
            {
                this.host = "ftp://" + dt.rows[0]["server_ip"].tostring();//oa
            }
 
            this.port = port;
            this.proxy = proxy;
            this.enablessl = enablessl;
            this.usebinary = usebinary;
            this.usepassive = usepassive;
            this.wait = new manualresetevent(false);
        }
    #endregion
 
    #region 变量
    #region 主机
    private string host = string.empty;
    /// <summary>
    /// 主机
    /// </summary>
    public string host
    {
      get
      {
        return this.host ?? string.empty;//如果左操作数为空则返回右操作数,不为空返回左操作数
      }
    }
    #endregion
 
    #region 登录用户名
    private string userid = string.empty;
    /// <summary>
    /// 登录用户名
    /// </summary>
    public string userid
    {
      get
      {
        return this.userid;
      }
    }
    #endregion
 
    #region 密码
    private string password = string.empty;
    /// <summary>
    /// 密码
    /// </summary>
    public string password
    {
      get
      {
        return this.password;
      }
    }
    #endregion
 
    #region 代理
    iwebproxy proxy = null;
    /// <summary>
    /// 代理
    /// </summary>
    public iwebproxy proxy
    {
      get
      {
        return this.proxy;
      }
      set
      {
        this.proxy = value;
      }
    }
    #endregion
 
    #region 端口
    private int port = 8022;
    /// <summary>
    /// 端口
    /// </summary>
    public int port
    {
      get
      {
        return port;
      }
      set
      {
        this.port = value;
      }
    }
    #endregion
 
    #region 设置是否允许ssl
    private bool enablessl = false;
    /// <summary>
    /// enablessl 
    /// </summary>
    public bool enablessl
    {
      get
      {
        return enablessl;
      }
    }
    #endregion
 
    #region 使用被动模式
    private bool usepassive = true;
    /// <summary>
    /// 被动模式
    /// </summary>
    public bool usepassive
    {
      get
      {
        return usepassive;
      }
      set
      {
        this.usepassive = value;
      }
    }
    #endregion
 
 
    #region 二进制方式
    private bool usebinary = true;
    /// <summary>
    /// 二进制方式
    /// </summary>
    public bool usebinary
    {
      get
      {
        return usebinary;
      }
      set
      {
        this.usebinary = value;
      }
    }
    #endregion
 
    #region 远端路径
    private string remotepath = "/";
    /// <summary>
    /// 远端路径
    /// <para>
    ///     返回ftp服务器上的当前路径(可以是 / 或 /a/../ 的形式)
    /// </para>
    /// </summary>
    public string remotepath
    {
      get
      {
        return remotepath;
      }
      set
      {
        string result = "/";
        if (!string.isnullorempty(value) && value != "/")
        {
          result = "/" + value.trimstart('/').trimend('/') + "/";
        }
        this.remotepath = result;
      }
    }
    #endregion
 
    private manualresetevent wait;
 
    public manualresetevent operationcomplete
    {
      get { return wait; }
    }
    #endregion
 
    #region 创建一个ftp连接
    /// <summary>
    /// 创建一个ftp请求
    /// </summary>
    /// <param name="url">请求地址</param>
    /// <param name="method">请求方法</param>
    /// <returns>ftp请求</returns>
    private ftpwebrequest createrequest(string url, string method)
    {
      //建立连接
      ftpwebrequest request = (ftpwebrequest)ftpwebrequest.create(new uri(url));
      request.credentials = new networkcredential(this.userid, this.password);
      request.proxy = this.proxy;
      request.keepalive = false;//命令执行完毕之后关闭连接
      request.usebinary = usebinary;
      request.usepassive = usepassive;
      request.enablessl = enablessl;
      request.method = method;
      return request;
 
    }
    #endregion
 
    #region 异步上传
    /// <summary>
    /// 把文件上传到ftp服务器的remotepath下
    /// </summary>
    /// <param name="localfile">本地文件信息</param>
    /// <param name="remotefilename">要保存到ftp文件服务器上的文件名称包含扩展名</param>
    /// <param name="isrename">是否重命名</param>
    /// <returns></returns>
    public bool uploadasync(string localfile, string remotefilename,bool isrename,string newname)
    {
      manualresetevent waitobject;
      ftpstate state = new ftpstate();
      if (file.exists(localfile))
      {
        string url = host.trimend('/') + remotepath + remotefilename;
 
        ftpwebrequest request = createrequest(url, webrequestmethods.ftp.uploadfile);
        state.request = request;
 
        state.filename = localfile;
 
        // get the event to wait on.
        waitobject = state.operationcomplete;
        request.begingetrequeststream(
          new asynccallback(endgetstreamcallback), state
      );
        waitobject.waitone();
 
        // the operations either completed or threw an exception.
        if (state.operationexception != null)
        {
          throw state.operationexception;
        }
        if (isrename)
        {
          if (this.checkfileexist(remotefilename))
          {
            if (this.rename(remotefilename, newname))
            {
              return true;
            }
          }
          else { throw new exception(string.format("远端文件不存在,{0}", remotefilename)); }
        }
        else 
        {
          return true;
        }
        
        return false;
      }
      throw new exception(string.format("本地文件不存在,文件路径:{0}", localfile));
    }
 
    private void endgetstreamcallback(iasyncresult ar)
    {
      ftpstate state = (ftpstate)ar.asyncstate;
 
      stream requeststream = null;
      // end the asynchronous call to get the request stream.
      try
      {
        requeststream = state.request.endgetrequeststream(ar);
        // copy the file contents to the request stream.
        const int bufferlength = 2048;
        byte[] buffer = new byte[bufferlength];
        int count = 0;
        int readbytes = 0;
        filestream stream = file.openread(state.filename);
        do
        {
          readbytes = stream.read(buffer, 0, bufferlength);
          requeststream.write(buffer, 0, readbytes);
          count += readbytes;
        }
        while (readbytes != 0);
        //console.writeline("writing {0} bytes to the stream.", count);
        // important: close the request stream before sending the request.
        requeststream.close();
        // asynchronously get the response to the upload request.
        state.request.begingetresponse(
            new asynccallback(endgetresponsecallback),
            state
        );
      }
      // return exceptions to the main application thread.
      catch (exception e)
      {
        
        state.operationexception = e;
        state.operationcomplete.set();
        //throw new exception("could not get the request stream.");
      }
 
    }
      
 
private void endgetresponsecallback(iasyncresult ar)
{
  ftpstate state = (ftpstate)ar.asyncstate;
  ftpwebresponse response = null;
  try
  {
    response = (ftpwebresponse)state.request.endgetresponse(ar);
    response.close();
    state.statusdescription = response.statusdescription;
    // signal the main application thread that 
    // the operation is complete.
    state.operationcomplete.set();
  }
  // return exceptions to the main application thread.
  catch (exception e)
  {
    state.operationexception = e;
    state.operationcomplete.set();
    //throw new exception("error getting response.");
  }
} 
    #endregion
 
    #region 上传一个文件到远端路径下
    /// <summary>
    /// 把文件上传到ftp服务器的remotepath下
    /// </summary>
    /// <param name="localfile">本地文件信息</param>
    /// <param name="remotefilename">要保存到ftp文件服务器上的文件名称包含扩展名</param>
    public bool upload(fileinfo localfile, string remotefilename)
    {
      bool result = false;
      if (localfile.exists)
      {
        string url = host.trimend('/') + remotepath + remotefilename;
 
        ftpwebrequest request = createrequest(url, webrequestmethods.ftp.uploadfile);
 
                //上传数据
                using (stream rs = request.getrequeststream())
                {
                    using (filestream fs = localfile.openread())
                    {
                        byte[] buffer = new byte[4096];//4k
                        int count = fs.read(buffer, 0, buffer.length);//每次从流中读4个字节再写入缓冲区
                        while (count > 0)
                        {
                            rs.write(buffer, 0, count);
                            count = fs.read(buffer, 0, buffer.length);
                        }
                        fs.close();
                        result = true;
                    }
                }
        return result;
      }
      throw new exception(string.format("本地文件不存在,文件路径:{0}", localfile.fullname));
    }
    #endregion
 
 
 
    #region 从ftp服务器上下载文件
    /// <summary>
    /// 从当前目录下下载文件
    /// <para>
    /// 如果本地文件存在,则从本地文件结束的位置开始下载.
    /// </para>
    /// </summary>
    /// <param name="servername">服务器上的文件名称</param>
    /// <param name="localname">本地文件名称</param>
    /// <returns>返回一个值,指示是否下载成功</returns>
    public bool download(string servername, string localname)
    {
            try
            {
                bool result = false;
                //string tempfilename = path.getdirectoryname(localname) + @"\" + path.getfilenamewithoutextension(localname) + ".tmp";
                if (file.exists(localname)) return true;
                using (filestream fs = new filestream(localname, filemode.openorcreate)) //创建或打开本地文件
                {
                    //建立连接
                    string url = host.trimend('/') + remotepath + servername;
                    ftpwebrequest request = createrequest(url, webrequestmethods.ftp.downloadfile);
                    request.contentoffset = fs.length;
                    using (ftpwebresponse response = (ftpwebresponse)request.getresponse())
                    {
                        fs.position = fs.length;
                        byte[] buffer = new byte[4096];//4k
                        int count = response.getresponsestream().read(buffer, 0, buffer.length);
                        while (count > 0)
                        {
                            fs.write(buffer, 0, count);
                            count = response.getresponsestream().read(buffer, 0, buffer.length);
                        }
                        response.getresponsestream().close();
                    }
                    result = true;
                }
                return result;
            }
            catch (exception ex) { throw ex; }
        }
    #endregion
 
    #region 重命名ftp服务器上的文件
    /// <summary>
    /// 文件更名
    /// </summary>
    /// <param name="oldfilename">原文件名</param>
    /// <param name="newfilename">新文件名</param>
    /// <returns>返回一个值,指示更名是否成功</returns>
    public bool rename(string oldfilename, string newfilename)
    {
      bool result = false;
      //建立连接
      string url = host.trimend('/') + remotepath + oldfilename;
      ftpwebrequest request = createrequest(url, webrequestmethods.ftp.rename);
      request.renameto = newfilename;
      using (ftpwebresponse response = (ftpwebresponse)request.getresponse())
      {
        result = true;
      }
      return result;
    }
    #endregion
 
    #region 从当前目录下获取文件列表
    /// <summary>
    /// 获取当前目录下文件列表
    /// </summary>
    /// <returns></returns>
    public list<string> getfilelist()
    {
            try
            {
                list<string> result = new list<string>();
                //建立连接
                string url = host.trimend('/') + remotepath;
                ftpwebrequest request = createrequest(url, webrequestmethods.ftp.listdirectory);
                using (ftpwebresponse response = (ftpwebresponse)request.getresponse())
                {
                    streamreader reader = new streamreader(response.getresponsestream(), system.text.encoding.default);//中文文件名
                    string line = reader.readline();
                    while (line != null)
                    {
                        result.add(line);
                        line = reader.readline();
                    }
                }
                return result;
            }
            catch (exception ex) { throw ex; }
    }
    #endregion
 
    #region 从ftp服务器上获取文件和文件夹列表
    /// <summary>
    /// 获取详细列表
    /// </summary>
    /// <returns></returns>
    public list<string> getfiledetails()
    {
      list<string> result = new list<string>();
      //建立连接
      string url = host.trimend('/') + remotepath;
      ftpwebrequest request = createrequest(url, webrequestmethods.ftp.listdirectorydetails);
      using (ftpwebresponse response = (ftpwebresponse)request.getresponse())
      {
        streamreader reader = new streamreader(response.getresponsestream(), system.text.encoding.default);//中文文件名
        string line = reader.readline();
        while (line != null)
        {
          result.add(line);
          line = reader.readline();
        }
      }
      return result;
    }
 
 
        public list<string> getfiledetails(string remotepath)
        {
            list<string> result = new list<string>();
            //建立连接
            string url = host.trimend('/') + remotepath;
            ftpwebrequest request = createrequest(url, webrequestmethods.ftp.listdirectorydetails);
            using (ftpwebresponse response = (ftpwebresponse)request.getresponse())
            {
                streamreader reader = new streamreader(response.getresponsestream(), system.text.encoding.default);//中文文件名
                string line = reader.readline();
                while (line != null)
                {
                    result.add(line);
                    line = reader.readline();
                }
            }
            return result;
        }
        #endregion
 
        #region 从ftp服务器上删除文件
        /// <summary>
        /// 删除ftp服务器上的文件
        /// </summary>
        /// <param name="filename">文件名称</param>
        /// <returns>返回一个值,指示是否删除成功</returns>
        public bool deletefile(string filename)
    {
      bool result = false;
      //建立连接
      string url = host.trimend('/') + remotepath + filename;
      ftpwebrequest request = createrequest(url, webrequestmethods.ftp.deletefile);
      using (ftpwebresponse response = (ftpwebresponse)request.getresponse())
      {
        result = true;
      }
 
      return result;
    }
    #endregion
 
    #region 在ftp服务器上创建目录
    /// <summary>
    /// 在当前目录下创建文件夹
    /// </summary>
    /// <param name="dirname">文件夹名称</param>
    /// <returns>返回一个值,指示是否创建成功</returns>
    public bool makedirectory(string dirname)
    {
      bool result = false;
      //建立连接
      string url = host.trimend('/') + remotepath + dirname;
      ftpwebrequest request = createrequest(url, webrequestmethods.ftp.makedirectory);
      using (ftpwebresponse response = (ftpwebresponse)request.getresponse())
      {
        result = true;
      }
      return result;
    }
    #endregion
 
    #region 从ftp服务器上删除目录
    /// <summary>
    /// 删除文件夹
    /// </summary>
    /// <param name="dirname">文件夹名称</param>
    /// <returns>返回一个值,指示是否删除成功</returns>
    public bool deletedirectory(string dirname)
    {
      bool result = false;
      //建立连接
      string url = host.trimend('/') + remotepath + dirname;
      ftpwebrequest request = createrequest(url, webrequestmethods.ftp.removedirectory);
      using (ftpwebresponse response = (ftpwebresponse)request.getresponse())
      {
        result = true;
      }
      return result;
    }
    #endregion
 
    #region 从ftp服务器上获取文件大小
    /// <summary>
    /// 获取文件大小
    /// </summary>
    /// <param name="filename"></param>
    /// <returns></returns>
    public long getfilesize(string filename)
    {
      long result = 0;
      //建立连接
      string url = host.trimend('/') + remotepath + filename;
      ftpwebrequest request = createrequest(url, webrequestmethods.ftp.getfilesize);
      using (ftpwebresponse response = (ftpwebresponse)request.getresponse())
      {
        result = response.contentlength;
      }
 
      return result;
    }
    #endregion
 
    #region 给ftp服务器上的文件追加内容
    /// <summary>
    /// 给ftp服务器上的文件追加内容
    /// </summary>
    /// <param name="localfile">本地文件</param>
    /// <param name="remotefilename">ftp服务器上的文件</param>
    /// <returns>返回一个值,指示是否追加成功</returns>
    public bool append(fileinfo localfile, string remotefilename)
    {
      if (localfile.exists)
      {
        using (filestream fs = new filestream(localfile.fullname, filemode.open))
        {
          return append(fs, remotefilename);
        }
      }
      throw new exception(string.format("本地文件不存在,文件路径:{0}", localfile.fullname));
    }
 
    /// <summary>
    /// 给ftp服务器上的文件追加内容
    /// </summary>
    /// <param name="stream">数据流(可通过设置偏移来实现从特定位置开始上传)</param>
    /// <param name="remotefilename">ftp服务器上的文件</param>
    /// <returns>返回一个值,指示是否追加成功</returns>
    public bool append(stream stream, string remotefilename)
    {
      bool result = false;
      if (stream != null && stream.canread)
      {
        //建立连接
        string url = host.trimend('/') + remotepath + remotefilename;
        ftpwebrequest request = createrequest(url, webrequestmethods.ftp.appendfile);
        using (stream rs = request.getrequeststream())
        {
          //上传数据
          byte[] buffer = new byte[4096];//4k
          int count = stream.read(buffer, 0, buffer.length);
          while (count > 0)
          {
            rs.write(buffer, 0, count);
            count = stream.read(buffer, 0, buffer.length);
          }
          result = true;
        }
      }
      return result;
    }
    #endregion
 
    #region 获取ftp服务器上的当前路径
    /// <summary>
    /// 获取ftp服务器上的当前路径
    /// </summary>
    public string currentdirectory
    {
      get
      {
        string result = string.empty;
        string url = host.trimend('/') + remotepath;
        ftpwebrequest request = createrequest(url, webrequestmethods.ftp.printworkingdirectory);
        using (ftpwebresponse response = (ftpwebresponse)request.getresponse())
        {
          string temp = response.statusdescription;
          int start = temp.indexof('"') + 1;
          int end = temp.lastindexof('"');
          if (end >= start)
          {
            result = temp.substring(start, end - start);
          }
        }
        return result;
 
      }
    }
    #endregion
 
    #region 检查当前路径上是否存在某个文件
    /// <summary>
    /// 检查文件是否存在
    /// </summary>
    /// <param name="filename">要检查的文件名</param>
    /// <returns>返回一个值,指示要检查的文件是否存在</returns>
    public bool checkfileexist(string filename)
    {
      bool result = false;
      if (filename != null && filename.trim().length > 0)
      {
        filename = filename.trim();
        list<string> files = getfilelist();
        if (files != null && files.count > 0)
        {
          if (files.count(q => q.tolower() == filename.tolower()) > 0)
            result = true;
        }
      }
      return result;
    }
        #endregion
 
 
        /// <summary>
        /// 判断当前目录下指定的子目录是否存在
        /// </summary>
        /// <param name="remotedirectoryname">指定的目录名</param>
        public bool checkdirectoryexist(string rootdir, string remotedirectoryname)
        {
            string[] dirlist = getdirectorylist(rootdir);//获取子目录
            if (dirlist.length > 0)
            {
                foreach (string str in dirlist)
                {
                    if (str.trim() == remotedirectoryname.trim())
                    {
                        return true;
                    }
                }
            }
            return false;
        }
 
 
        //获取子目录
        public string[] getdirectorylist(string dirname)
        {
            string[] drectory = getfiledetails(dirname).toarray();
            list<string> strlist = new list<string>();
            if (drectory.length > 0)
            {
                foreach (string str in drectory)
                {
                    if (str.trim().length == 0)
                        continue;
                    //会有两种格式的详细信息返回
                    //一种包含<dir>
                    //一种第一个字符串是drwxerwxx这样的权限操作符号
                    //现在写代码包容两种格式的字符串
                    if (str.trim().contains("<dir>"))
                    {
                        strlist.add(str.substring(39).trim());
                    }
                    else
                    {
                        if (str.trim().substring(0, 1).toupper() == "d")
                        {
                            strlist.add(str.substring(55).trim());
                        }
                    }
                }
            }
            return strlist.toarray();
        }
    }

到此这篇关于c#中ftp常用操作的示例代码的文章就介绍到这了,更多相关c# ftp操作内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com