c#如何在FTP服务器上下载文件夹及子文件夹中的文件

c#从FTP服务器上下载文件夹及子文件夹中的文件需要三个步骤。

1.单个文件的下载

/*adss表示存放到本地的路径名,ftpadss表示从FTP服务器下载的路径名*/

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;
            downRequest.KeepAlive = true;
            FtpWebResponse response = (FtpWebResponse)downRequest.GetResponse();
            Stream ftpStream = response.GetResponseStream();
            long c1 = response.ContentLength;
            int bufferSize = 65536;
            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();
        }

2.遍历单个文件夹下的所有文件的名称,存到一个数组中。

 public string[] getFtpList(string ftpads, string name, string type)
        {
            WebResponse webresp = null;
            StreamReader ftpFileListReader = null;
            FtpWebRequest ftpRequest = null;
            try
            {
                ftpRequest = (FtpWebRequest)WebRequest.Create(new Uri(ftpads + name));
                ftpRequest.Method = type;
                webresp = ftpRequest.GetResponse();
                ftpFileListReader = new StreamReader(webresp.GetResponseStream(), Encoding.UTF8);
            }
            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();
            }
            ftpFileListReader.Close();
            webresp.Close();
            string[] ftpFileList = str.ToString().Split('\n');
            return ftpFileList;
        }

3.递归文件夹,获取文件夹及子文件夹中的文件

public void downFtp(string ftpads, string name, string Myads)
        {
            string downloadDir = Myads + name;
            string ftpdir = ftpads + name;
            string[] fullname = getFtpList(ftpads, name, WebRequestMethods.Ftp.ListDirectoryDetails);
                         
            string[] onlyname = getFtpList(ftpads, name, WebRequestMethods.Ftp.ListDirectory);
         
            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);

                            }
                        }
                    }
                }
            }
        }

以上三个方法是最核心的三个方法,登陆FTP服务器需要用户名和密码,因此可以在App.config中进行设置。

下面是我自己用于配置的文件的路径,大家可以做一个参照。

<configuration>
  <appSettings>
    <add key="FtpServerMain" value="ftp://192.168.232.1:2121/主站模板"/>
    <add key="FtpServerRelay" value="ftp://192.168.232.1:2121/中继站模板"/>
    <add key="FtpServerMainTemp" value="ftp://192.168.232.1:2121/主站临站模板"/>
    <add key="FtpServerRelayTemp" value="ftp://192.168.232.1:2121/中继站临站模板"/>
    <add key="FtpDefaultUrlTest" value="ftp://192.168.232.1:2121/测试相关/测试配置文件"/>
    <add key="FtpDefaultUrlRelease" value="ftp://192.168.232.1:2121/发布数据"/>
    <add key="LoginID" value="ftp"/>
    <add key="LoginPWD" value="123"/>
    <add key="DownloadPath" value="D://"/>
  </appSettings>
</configuration>

以上是从FTP服务器上下载文件夹及子文件夹中所有的文件,这个是我自己亲身实践通过的。如果大家有任何问题,请随时在底下评论。

猜你喜欢

转载自blog.csdn.net/qq_37764098/article/details/84105356