下载FTP服务器所有文件

/// <summary>
        /// 下载所有文件
        /// </summary>
        /// <param name="username">FTP用户名</param>
        /// <param name="password">FTP密码</param>
        /// <param name="ftpUrl">FTP URL</param>
        /// <param name="ftpPath">FTP 路径</param>
        /// <param name="savePath">保存路径</param>
        public static void DownLoadAllFiles(String userName, String pwd, String ftpUrl, String ftpPath, String savePath)
        {
            DownLoadFile(userName, pwd, ftpUrl, "", savePath);
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="userName">FTP用户名</param>
        /// <param name="pwd">FTP密码</param>
        /// <param name="ftpUrl">FTP URL</param>
        /// <param name="ftpPath">FTP 路径</param>
        /// <param name="savePath">保存路径</param>
        private static void DownLoadFile(String userName, String pwd, String ftpUrl, String ftpPath, String savePath)
        {
            // 如果目录不存在
            if (!Directory.Exists(savePath))
            {
                Directory.CreateDirectory(savePath);
            }
            List<String> fileNames = GetFile(userName, pwd, ftpUrl, ftpPath);
            fileNames.ForEach(file =>
            {
                DownloadFtpFile(userName, pwd, ftpUrl + "//" + ftpPath + "//" + file, savePath, file);
            });
            // 获取所有目录
            List<String> lsDir = GetDirctory(userName, pwd, ftpUrl, ftpPath);
            lsDir.ForEach(dir =>
            {
                DownLoadFile(userName, pwd, ftpUrl + "//" + ftpPath, dir, savePath + "//" + dir);
            });
        }

        /// <summary>
        ///从ftp服务器上下载文件的功能
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="pwd"></param>
        /// <param name="ftpUrl">ftp地址</param>
        /// <param name="filePath"></param>
        /// <param name="fileName"></param>
        public static void DownloadFtpFile(String userId, String pwd, String ftpUrl, String filePath, String fileName)
        {
            FtpWebRequest reqFTP = null;
            FtpWebResponse response = null;
            try
            {
                String onlyFileName = Path.GetFileName(fileName);

                String downFileName = filePath + "\\" + onlyFileName;
                String url = ftpUrl;
                if (File.Exists(downFileName))
                {
                    //DeleteDir(downFileName);
                }
                // 如果目录不存在
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }

                FileStream outputStream = new FileStream(downFileName, FileMode.Create);

                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));
                reqFTP.Credentials = new NetworkCredential(userId, pwd);
                reqFTP.UseBinary = true;
                reqFTP.UsePassive = true;
                reqFTP.KeepAlive = true;
                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                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();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

  获取目录中文件列表

/// <summary>
        /// 从ftp服务器上获得文件列表
        /// </summary>
        /// <param name="username">FTP用户名</param>
        /// <param name="password">FTP密码</param>
        /// <param name="path">FTP URL</param>
        /// <param name="RequedstPath">服务器下的相对路径</param>
        /// <returns></returns>
        public static List<String> GetFile(String username, String password, String path, String RequedstPath)
        {
            List<String> strs = new List<String>();
            try
            {
                String uri = path + "//" + RequedstPath;  //目标路径 path为服务器地址
                FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                // ftp用户名和密码
                reqFTP.Credentials = new NetworkCredential(username, password);
                reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                WebResponse response = reqFTP.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());//中文文件名

                String line = reader.ReadLine();
                while (line != null)
                {
                    if (!line.Contains("<DIR>"))
                    {
                        String msg = line.Substring(39).Trim();
                        strs.Add(msg);
                    }
                    line = reader.ReadLine();
                }
                reader.Close();
                response.Close();
                return strs;
            }
            catch (Exception ex)
            {
                Console.WriteLine("获取文件出错:" + ex.Message);
            }
            return strs;
        }

  获取文件夹下目录列表

/// <summary>
        /// 从ftp服务器上获得文件夹列表
        /// </summary>
        /// <param name="username">FTP用户名</param>
        /// <param name="password">FTP密码</param>
        /// <param name="path">FTP URL</param>
        /// <param name="RequedstPath">服务器下的相对路径</param>
        /// <returns></returns>
        public static List<String> GetDirctory(String username, String password, String path, String RequedstPath)
        {
            List<String> strs = new List<String>();
            try
            {
                String uri = path + "//" + RequedstPath;  //目标路径 path为服务器地址
                FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                // ftp用户名和密码
                reqFTP.Credentials = new NetworkCredential(username, password);
                reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                WebResponse response = reqFTP.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());//中文文件名

                String line = reader.ReadLine();
                while (line != null)
                {
                    if (line.Contains("<DIR>"))
                    {
                        String msg = line.Substring(line.LastIndexOf("<DIR>") + 5).Trim();
                        strs.Add(msg);
                    }
                    line = reader.ReadLine();
                }
                reader.Close();
                response.Close();
                return strs;
            }
            catch (Exception ex)
            {
                Console.WriteLine("获取目录出错:" + ex.Message);
            }
            return strs;
        }

  

posted @ 2020-06-16 16:32  沙漠狼  阅读(859)  评论(0编辑  收藏  举报