如何在Windows应用程序中下载ftp服务器文件夹和文件c#

时间:2016-11-28 06:09:25

标签: c# ftp

在我的应用程序中,我有一个包含一些文件夹的FTP服务器,这些文件夹包含多个文件,一些文件夹是空文件夹。我需要将所有文件夹和文件下载到我的本地文件夹中。如何将它们下载到我的本地文件夹?

我使用下面的代码并得到例外:

public void DownloadFtpDirectory(string url, NetworkCredential credentials, string localPath)
{
    FtpWebRequest listRequest = (FtpWebRequest)WebRequest.Create(url);
    listRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
    listRequest.Credentials = credentials;

    List<string> lines = new List<string>();

    using (FtpWebResponse listResponse = (FtpWebResponse)listRequest.GetResponse())
    using (Stream listStream = listResponse.GetResponseStream())
    using (StreamReader listReader = new StreamReader(listStream))
    {
        while (!listReader.EndOfStream)
        {
            lines.Add(listReader.ReadLine());
        }
    }

    foreach (string line in lines)
    {
        string[] tokens =
        line.Split(new[] { ' ' }, 9, StringSplitOptions.RemoveEmptyEntries);
        string name = tokens[8];
        string permissions = tokens[0];

        string localFilePath = Path.Combine(localPath, name);
        string fileUrl = url + name;

        if (permissions[0] == 'c')
        {
            if (!Directory.Exists(localFilePath))
            {
                Directory.CreateDirectory(localFilePath);
            }
            DownloadFtpDirectory(fileUrl + "/", credentials, localFilePath);
        }
        else
        {
            FtpWebRequest downloadRequest = (FtpWebRequest)WebRequest.Create(fileUrl);
            downloadRequest.Method = WebRequestMethods.Ftp.DownloadFile;
            downloadRequest.Credentials = credentials;

            using (FtpWebResponse downloadResponse = (FtpWebResponse)downloadRequest.GetResponse())
            using (Stream sourceStream = downloadResponse.GetResponseStream())
            using (Stream targetStream = File.Create(localFilePath))
            {
                byte[] buffer = new byte[10240];
                int read;
                while ((read = sourceStream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    targetStream.Write(buffer, 0, read);
                }
            }
        }
    }
}

enter image description here Exception

0 个答案:

没有答案