Home > Backend Development > C++ > How can I recursively download files and subdirectories from an FTP server using C#?

How can I recursively download files and subdirectories from an FTP server using C#?

DDD
Release: 2025-01-12 15:01:43
Original
535 people have browsed it

Use C# to recursively download files and subdirectories on an FTP server

Question:

The current code only lists and downloads files in the specified FTP directory, but cannot download subdirectories and subfiles. Additionally, when trying to download the folder as a file, the server returns a 550 error.

Solution:

Implement recursive directory listing and download operations:

Recursive directory listing:

  1. List remote directories using protocol-specific commands such as LIST or MLSD.
  2. Parse directory listings to identify files and directories.
  3. If the entry is a file, use the DownloadFile method to download it.
  4. If the entry is a directory, recursively list and download its contents.

Identify files from subdirectories:

Since FtpWebRequest has no explicit way to achieve this, the alternative is:

  • Attempt an operation that is valid for files but not for directories (e.g., DownloadFile).
  • Identifies files based on filename patterns (e.g. all files have an extension).
  • Use server-specific directory listing format (e.g. look for a directory with a "d" at the beginning of the line in a Unix-style listing).

Example recursive download code:

<code class="language-csharp">void DownloadFtpDirectory(string url, NetworkCredential credentials, string localPath)
{
    // 列出目录详细信息
    FtpWebRequest listRequest = (FtpWebRequest)WebRequest.Create(url);
    listRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
    listRequest.Credentials = credentials;

    var lines = new List<string>();
    using (var listResponse = (FtpWebResponse)listRequest.GetResponse())
    using (var listStream = listResponse.GetResponseStream())
    using (var listReader = new StreamReader(listStream))
    {
        while (!listReader.EndOfStream)
        {
            lines.Add(listReader.ReadLine());
        }
    }

    // 迭代目录条目
    foreach (var line in lines)
    {
        var tokens = line.Split(' ', 9, StringSplitOptions.RemoveEmptyEntries);
        var name = tokens[8];
        var permissions = tokens[0];

        var localFilePath = Path.Combine(localPath, name);
        var fileUrl = url + name + "/";

        // 如果是目录,则递归
        if (permissions[0] == 'd')
        {
            if (!Directory.Exists(localFilePath))
            {
                Directory.CreateDirectory(localFilePath);
            }

            DownloadFtpDirectory(fileUrl, credentials, localFilePath);
        }
        // 如果是文件,则下载
        else
        {
            var downloadRequest = (FtpWebRequest)WebRequest.Create(fileUrl);
            downloadRequest.Method = WebRequestMethods.Ftp.DownloadFile;
            downloadRequest.Credentials = credentials;

            using (FtpWebResponse downloadResponse = (FtpWebResponse)downloadRequest.GetResponse())
            using (var sourceStream = downloadResponse.GetResponseStream())
            using (var 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);
                }
            }
        }
    }
}</code>
Copy after login

Usage:

<code class="language-csharp">var credentials = new NetworkCredential("user", "password");
var url = "ftp://ftp.example.com/directory/to/download/";
var localPath = @"C:\target\directory";
DownloadFtpDirectory(url, credentials, localPath);</code>
Copy after login

Alternatively, consider using a third-party library like WinSCP, which supports recursive directory operations and can handle various FTP server formats.

How can I recursively download files and subdirectories from an FTP server using C#?

The above is the detailed content of How can I recursively download files and subdirectories from an FTP server using C#?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template