当前位置:   article > 正文

C# 操作FTP_c# 对ftp文件进行增删改

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;
            }
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

上传文件

		/// <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;
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65

下载文件

		/// <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;
           }
       }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34

获取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;
       }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56

创建目录

  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;
       }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

删除文件

		/// <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);
            }
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/199808
推荐阅读
相关标签
  

闽ICP备14008679号