FTP单/多文件(文件夹)上传下载,判断是否为文件夹,获取指定路径文件夹名称

时间:2021-01-17 12:30:47
using System;
using System.Text;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;

namespace UpdateApp
{
    class fuck
    {
        public static void RConfig() { 
        
        }


        /// <summary>
        /// 检查服务器是否需要更新
        /// </summary>
        /// <param name="FtpServerIP">服务器IP</param>
        /// <returns></returns>
        public bool CheckUpdataFromServer(string FtpServerIP)
        {
            //to do 检查服务器是否需要更新
            string[] value = getFileList(FtpServerIP);
            if (value == null)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="FtpIp">服务器IP</param>
        /// <returns></returns>
        public static string[] getFileList(string FtpIp)
        {
            StringBuilder result = new StringBuilder();
            try
            {
                FtpWebRequest reqFtp = FtpWebRequest.Create(FtpIp) as FtpWebRequest;
                reqFtp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                WebResponse webRp = reqFtp.GetResponse();
                StreamReader reader = new StreamReader(webRp.GetResponseStream());
                string line = reader.ReadLine();
                while (line != null)
                {
                    result.Append(line);
                    result.Append("\n");
                    line = reader.ReadLine();
                }
                reader.Close();
                webRp.Close();
                return result.ToString().Split('\n');
            }
            catch
            {
                return null;
            }
        }





        /// <summary>  
        /// 单个文件下载方法  
        /// </summary>  
        /// <param name="adss">保存文件的本地路径</param>  
        /// <param name="ftpadss">下载文件的FTP路径</param>  
        public void download(string adss, string ftpadss)
        {

            //FileMode常数确定如何打开或创建文件,指定操作系统应创建新文件。  
            //FileMode.Create如果文件已存在,它将被改写  
            FileStream outputStream = new FileStream(adss, FileMode.Create);
            FtpWebRequest downRequest = (FtpWebRequest)WebRequest.Create(new Uri(ftpadss));
            //设置要发送到 FTP 服务器的命令  
            downRequest.Method = WebRequestMethods.Ftp.DownloadFile;
            FtpWebResponse response = (FtpWebResponse)downRequest.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();
        }



        /// </summary>  
        /// <param name="ftpads">FTP地址路径</param>  
        /// <param name="name">所选择的文件或者文件夹名字</param>  
        /// <param name="type">要发送到FTP服务器的命令</param>  
        /// <returns></returns>  
        public string[] ftp(string ftpads, string name)
        {
            WebResponse webresp = null;
            StreamReader ftpFileListReader = null;
            FtpWebRequest ftpRequest = null;
            try
            {
                ftpRequest = (FtpWebRequest)WebRequest.Create(new Uri(ftpads + name));
                ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                ftpRequest.UseBinary = true;
                webresp = ftpRequest.GetResponse();

                ftpFileListReader = new StreamReader(webresp.GetResponseStream(), Encoding.Default);
            }
            catch (Exception ex)
            {
                ex.ToString();

            }
            StringBuilder str = new StringBuilder();
            string line = ftpFileListReader.ReadLine();

            while (line != null)
            {
                str.Append(line);
                str.Append("\n");
                line = ftpFileListReader.ReadLine();
            }
            str.Remove(str.ToString().LastIndexOf('\n'), 1);
            string[] fen = str.ToString().Split('\n');
            StringBuilder fileNames = new StringBuilder();
            foreach (string tmpName in fen)
            {
                string tmpStr = Regex.Replace(tmpName, "  *", " ");
                //string fileName = tmpStr.Split(' ')[3];
                string fileName = tmpName.Remove(0, tmpName.IndexOf(tmpStr.Split(' ')[3]));
                fileNames.Append(fileName);
                fileNames.Append("\n");
            }
            return fileNames.ToString().Trim().Split('\n');
        }



        /// <summary>  
        /// 下载方法KO  
        /// downftp("ftp://192.168.0.4/", "ftpfile", "D://1210/");
        /// </summary>  
        /// <param name="ftpads">FTP路径</param>  
        /// <param name="name">需要下载文件名</param>  
        /// <param name="Myads">保存的本地路径</param>  
        public void downftp(string ftpads, string name, string Myads)
        {
            string downloadDir = Myads + name;
            string ftpdir = ftpads + name;
            string[] fullname = ftp(ftpads, name);
            //判断是否为单个文件   
            if (fullname.Length <= 2)
            {
                if (fullname[fullname.Length - 1] == "")
                {
                    download(downloadDir + "/" + name, ftpads + name + "/" + name);
                }
            }
            else
            {
                string[] onlyname = ftp(ftpads, name);
                if (!Directory.Exists(downloadDir))
                {
                    Directory.CreateDirectory(downloadDir);
                }
                foreach (string names in fullname)
                {
                    //判断是否具有文件夹标识<DIR>  
                    if (names.Contains("<DIR>"))
                    {
                        string olname = names.Split(new string[] { "<DIR>" },
                        StringSplitOptions.None)[1].Trim();
                        downftp(ftpdir, "//" + olname, downloadDir);
                    }
                    else
                    {
                        foreach (string onlynames in onlyname)
                        {
                            if (onlynames == "" || onlynames == " " || names == "")
                            {
                                break;
                            }
                            else
                            {
                                //if (names.Contains(" " + onlynames))
                                // {
                                download(downloadDir + "/" + onlynames, ftpads + name + "/" + onlynames);
                                //break;
                                // }
                            }
                        }
                    }
                }
            }
        }
    }
}




f.CheckUpdataFromServer("ftp://192.168.0.4/fuck2");