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

How to transfer multiple files from FTP server to local directory using C#?(如何使用 C# 将多个文件从 FTP 服务器传输到本地目录?)
本文介绍了如何使用 C# 将多个文件从 FTP 服务器传输到本地目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I can transfer one file from ftp server to local directory. using the following code

  using (WebClient ftpClient = new WebClient())
        {
            ftpClient.Credentials = new System.Net.NetworkCredential("username", "password");
            ftpClient.DownloadFile("ftp://website.com/abcd.docx", @"D:\WestHam	est.docx");

但我不知道如何传输多个文件.任何人都可以帮我解决这个问题.}

but i don't know how to transfer multiple files. can anybody help me on this. }

推荐答案

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

Use this code, just replace the user credentials:

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);
            }
        }
    }

这篇关于如何使用 C# 将多个文件从 FTP 服务器传输到本地目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)