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:
Identify files from subdirectories:
Since FtpWebRequest has no explicit way to achieve this, the alternative is:
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>
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>
Alternatively, consider using a third-party library like WinSCP, which supports recursive directory operations and can handle various FTP server formats.
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!