C# 操作FTP

检查是否正常连接

  		/// <summary>
        /// 检查是否能正常连接FTP服务器
        /// </summary>
        /// _ftpServerIP   IP +端口号
        /// _ftpUserID 用户名,_ftpPassword 密码
        /// <returns></returns>
 public bool CheckFtp(string _ftpServerIP ,string _ftpUserID,string _ftpPassword) {
            try {
                FtpWebRequest ftprequest = (FtpWebRequest)WebRequest.Create(new Uri("ftp://" + _ftpServerIP + "/"));
                ftprequest.Credentials = new NetworkCredential(_ftpUserID, _ftpPassword);
                ftprequest.Method = WebRequestMethods.Ftp.ListDirectory;
                ftprequest.Timeout = 600000;
                FtpWebResponse ftpResponse = (FtpWebResponse)ftprequest.GetResponse();
                ftpResponse.Close();
                return true;
            } catch (Exception ex) { 
                return false;
            }
        }

上传文件

		/// <summary>
        /// 上传文件到FTP服务器
        /// </summary>
        /// filename 要上传的文件
        /// ftp ftp ip+端口号
        ///  UserName 、Password 
        /// ftpPath   ftp 文件目录
        /// <returns></returns>
 public bool Upload(string filename,string ftp, string UserName, string Password,string ftpPath  )
        {
            try
            {
                bool b = CreateDir(ftp, UserName, Password, ftpPath);

                FileInfo fileInf = new FileInfo(filename);
                string uri = ftp + ftpPath + fileInf.Name;
                FtpWebRequest reqFTP  ;
                // 根据uri创建FtpWebRequest对象 
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                // ftp用户名和密码
                reqFTP.Credentials = new NetworkCredential(UserName, Password);
                //判断是否存在当前路径,如果不存在,就创建路径 
                // 默认为true,连接不会被关闭
                // 在一个命令之后被执行
                reqFTP.KeepAlive = false;
                reqFTP.Timeout = 60000;
                reqFTP.ServicePoint.ConnectionLimit = 10;
                //reqFTP.ServicePoint.Expect100Continue = false;
                // 指定执行什么命令
                reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
                // 指定数据传输类型
                reqFTP.UseBinary = true;
                // 上传文件时通知服务器文件的大小
                reqFTP.ContentLength = fileInf.Length;
                Total = (int)fileInf.Length;
                Size = 0;
                // 缓冲大小设置为2kb
                int buffLength = 2048;
                byte[] buff = new byte[buffLength];
                int contentLen;
                // 打开一个文件流 (System.IO.FileStream) 去读上传的文件
                FileStream fs = fileInf.OpenRead();
                // 把上传的文件写入流
                Stream strm = reqFTP.GetRequestStream();
                // 每次读文件流的2kb
                contentLen = fs.Read(buff, 0, buffLength);
                // 流内容没有结束
                while (contentLen != 0)
                {
                    // 把内容从file stream 写入 upload stream
                    strm.Write(buff, 0, contentLen);
                    contentLen = fs.Read(buff, 0, buffLength);
                    Size += contentLen;
                }
                // 关闭两个流
                strm.Close();
                fs.Close();
                reqFTP.Abort();
            }
            catch (Exception ex)
            {
                return false; 
            }
            return true;
        }

下载文件

		/// <summary>
       /// FTP下载方法
       /// </summary>
       /// <param name="filePath">下载文件存储路径</param>
       /// <param name="fileName">下载文件名称</param>
       public bool Download(string ftp, string UserName, string Password,string filePath, string fileName) {
           FtpWebRequest reqFTP=(FtpWebRequest)WebRequest.Create(new Uri(ftp));  
           reqFTP.UseBinary = true;
           reqFTP.Credentials = new NetworkCredential(UserName, Password);
           try {
               FileStream outputStream = new FileStream(filePath+ fileName, FileMode.Create);
               reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftp+ fileName));
               reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
               reqFTP.UseBinary = true;
               reqFTP.Credentials = new NetworkCredential(_ftpUserID, _ftpPassword);
               FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
               Stream ftpStream = response.GetResponseStream();
               long cl = response.ContentLength;
               int bufferSize = 2048;
               int readCount;
               byte[] buffer = new byte[bufferSize];
               readCount = ftpStream.Read(buffer, 0, bufferSize);
               while (readCount > 0) {
                   outputStream.Write(buffer, 0, readCount);
                   readCount = ftpStream.Read(buffer, 0, bufferSize);
               }
               ftpStream.Close();
               outputStream.Close();
               response.Close();
               return true;
           } catch (Exception ex) { 
               return false;
           }
       }

获取ftp目录下文件信息

  public static Regex FtpListDirectoryDetailsRegex = new Regex(@".*(?<month>(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec))\s*(?<day>[0-9]*)\s*(?<yearTime>([0-9]|:)*)\s*(?<fileName>.*)", RegexOptions.Compiled | RegexOptions.IgnoreCase);

       public List<FtpMsg> GetFtpMsgInfo(string ftp, string UserName, string Password,string upTime)
       {
           List<FtpMsg> listMsg = new List<FtpMsg>();
           FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(new Uri(ftp));
           ftpRequest.UseBinary = true;
           ftpRequest.Credentials = new NetworkCredential(UserName, Password);
           if (ftpRequest != null)
           {
               StringBuilder fileListBuilder = new StringBuilder();
               ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
               try
               {
                   WebResponse ftpResponse = ftpRequest.GetResponse();
                   StreamReader ftpFileListReader = new StreamReader(ftpResponse.GetResponseStream(), Encoding.Default); 
                   string line = ftpFileListReader.ReadLine();
                   while (line != null)
                   {
                       fileListBuilder.Append(line);
                       fileListBuilder.Append("@");//每个文件名称之间用@符号隔开,便于前端调用的时候解析
                       line = ftpFileListReader.ReadLine(); 
                   }
                   ftpFileListReader.Close();
                   ftpResponse.Close();
                   fileListBuilder.Remove(fileListBuilder.ToString().LastIndexOf("@"), 1); 
                   string[] fileNames = fileListBuilder.ToString().Split('@');//返回得到的数组 
                   // 目录详细
                   //-rw - rw - rw - 1 user group        2060 Mar  2 23:56 REPO03021600.0784
   				//-rw-rw-rw-   1 user     group         118 Mar  3 00:08 REPO03021611.0794
                   for (int i = 0; i < fileNames.Length; i++)
                   {
                       FtpMsg fmsg = new FtpMsg();
                       if (fileNames[i].Contains("rw"))
                       {
                           Match match = FtpListDirectoryDetailsRegex.Match(fileNames[i]);
                           string month = match.Groups["month"].Value; //Mar
                           string day = match.Groups["day"].Value; //2
                           string yearTime = match.Groups["yearTime"].Value;//23:56
                           string fileName = match.Groups["fileName"].Value;//REPO03021600.0784
                           string  fmsgTime=  Convert.ToDateTime(DateTime.Now.ToString("yy") + month + day ).ToString("yyyy-MM-dd")+ " "+yearTime;
                           fmsg.MSG_NAME = fileName;
                           fmsg.MSG_PATT = ftp + "/" + fileName; 
                           fmsg.MSG_TIME =Convert.ToDateTime( fmsgTime); 
                           listMsg.Add(fmsg); 
                       }
                   }
               }
               catch (Exception ex)
               {

                   throw;
               }
           }
           return listMsg;
       }

创建目录

  public bool FtpMakeDir(string strPath) {
           FtpWebRequest req = (FtpWebRequest)FtpWebRequest.Create(strPath);
           req.UseBinary = true;  
           req.Credentials = new NetworkCredential(_ftpUserID, _ftpPassword);
           req.Method = WebRequestMethods.Ftp.MakeDirectory;
           try {
               FtpWebResponse response = (FtpWebResponse)req.GetResponse();
               response.Close();
           } catch (Exception) {
               req.Abort();
               return false;
           }
           req.Abort();
           return true;
       }

删除文件

		/// <summary>
        /// 删除FTP文件
        /// </summary>
        /// <param name="fileName"></param>
        public void Delete(string filePath) {
            FtpWebRequest reqFTP;
            try {
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(filePath));

                reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;

                reqFTP.UseBinary = true;

                reqFTP.Credentials = new NetworkCredential(_ftpUserID, _ftpPassword);

                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                response.Close();
            } catch (Exception ex) {
                MessageBox.Show("删除FTP文件异常!" + ex.Message + "请联系信息管理部!", "异常", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
  • 7
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值