如何使用C#将多个文件从FTP服务器传输到本地目录?

如何使用C#将多个文件从FTP服务器传输到本地目录?,c#,ftp,webclient,transfer,C#,Ftp,Webclient,Transfer,我可以将一个文件从ftp服务器传输到本地目录。使用以下代码 using (WebClient ftpClient = new WebClient()) { ftpClient.Credentials = new System.Net.NetworkCredential("username", "password"); ftpClient.DownloadFile("ftp://website.com/abcd.docx", @"

我可以将一个文件从ftp服务器传输到本地目录。使用以下代码

  using (WebClient ftpClient = new WebClient())
        {
            ftpClient.Credentials = new System.Net.NetworkCredential("username", "password");
            ftpClient.DownloadFile("ftp://website.com/abcd.docx", @"D:\\WestHam\test.docx");
但我不知道如何传输多个文件。有人能帮我吗。
}

使用此代码,只需更换用户凭据:

static void Main(string[] args)
{
    FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create("ftp://mywebsite.com/");
    ftpRequest.Credentials = new NetworkCredential("user345", "pass234");
    ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
    FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse();
    StreamReader streamReader = new StreamReader(response.GetResponseStream());           
    List<string> directories = new List<string>();            

    string line = streamReader.ReadLine();
    while (!string.IsNullOrEmpty(line))
    {
        directories.Add(line);
        line = streamReader.ReadLine();
    }
    streamReader.Close();


    using (WebClient ftpClient = new WebClient())
    {
        ftpClient.Credentials = new System.Net.NetworkCredential("user345", "pass234");

        for (int i = 0; i <= directories.Count-1; i++)
        {
            if (directories[i].Contains("."))
            {

                string path = "ftp://mywebsite.com/" + directories[i].ToString();
                string trnsfrpth = @"D:\\Test\" + directories[i].ToString();
                ftpClient.DownloadFile(path, trnsfrpth);
            }
        }
    }
static void Main(字符串[]args)
{
FtpWebRequest ftpRequest=(FtpWebRequest)WebRequest.Create(“ftp://mywebsite.com/");
ftpRequest.Credentials=新的网络凭证(“user345”、“pass234”);
ftpRequest.Method=WebRequestMethods.Ftp.ListDirectory;
FtpWebResponse响应=(FtpWebResponse)ftpRequest.GetResponse();
StreamReader StreamReader=新的StreamReader(response.GetResponseStream());
列表目录=新列表();
string line=streamReader.ReadLine();
而(!string.IsNullOrEmpty(line))
{
目录。添加(行);
line=streamReader.ReadLine();
}
streamReader.Close();
使用(WebClient ftpClient=new WebClient())
{
ftpClient.Credentials=新系统.Net.NetworkCredential(“user345”、“pass234”);

对于(inti=0;i非常伟大和简单的库

看看吧

我的配置文件:


还有一个小小的FTP库:

namespace FTPDownloadAdapter {
    class Program
    {
        private static readonly string FtpHost = ConfigurationManager.AppSettings["FtpHost"];
        private static readonly string FtpUser = ConfigurationManager.AppSettings["FtpUser"];
        private static readonly string FtpPassword = ConfigurationManager.AppSettings["FtpPassword"];
        private static readonly string FtpDirectory = ConfigurationManager.AppSettings["FtpDirectory"];
        private static readonly string FileExtension = ConfigurationManager.AppSettings["FileExtension"];
        private static readonly string DownloadTo = ConfigurationManager.AppSettings["DownloadTo"];
        private static readonly string DeleteFilesAfterDownload = ConfigurationManager.AppSettings["DeleteFilesAfterDownload"];

        static void Main(string[] args)
        {


            try{


                DownloadFiles();


            }
            catch (Exception er){
                Console.WriteLine(er.ToString());
            }

        }

        private static void DownloadFiles(){

            // create an FTP client
            var client = new FtpClient(FtpHost) { Credentials = new NetworkCredential(FtpUser, FtpPassword) };

            // if you don't specify login credentials, we use the "anonymous" user account


            // begin connecting to the server
            client.Connect();


            Console.WriteLine($"Retrieving files with extension [{FileExtension}] from directory [{FtpDirectory}]");



            foreach (FtpListItem item in client.GetListing(FtpDirectory)){

                // if this is a file
                if (item.Type == FtpFileSystemObjectType.File && (Path.GetExtension(item.FullName) == FileExtension)){

                    // get the file size
                    long size = client.GetFileSize(item.FullName);

                    // get modified date/time of the file or folder
                    DateTime time = client.GetModifiedTime(item.FullName);

                    // calculate a hash for the file on the server side (default algorithm)
                    FtpHash hash = client.GetHash(item.FullName);

                    // download the file 
                    var fileName = Path.GetFileName(item.FullName);
                    var saveFilePath = Path.Combine(DownloadTo, fileName ?? throw new InvalidOperationException("File Appears to not have a name"));

                    Console.WriteLine($"Downloading file: {fileName}");

                    client.DownloadFile(localPath: saveFilePath, remotePath: item.FullName);

                    if (DeleteFilesAfterDownload == "true")
                    {
                        Console.WriteLine($"DeleteFilesAfterDownload is true, Deleting file from FTP : {item.FullName}");

                        client.DeleteFile(item.FullName);

                        Console.WriteLine("File deletion success");
                    }
                    else
                    {

                        Console.WriteLine($"DeleteFilesAfterDownload not true, skip deleting : {item.FullName}");

                    }

                }
            }
        }
    }
}

您是在询问并发下载吗?如果是这样,您需要为每个并发下载创建一个单独的WebClient对象,并在每个WebClient实例上调用DownloadFileAsync(不要忘记为其DownloadFileCompleted事件添加一个处理程序。)@Anjali只要替换ftp凭据,一切都会正常工作