当使用C#实现稳定的FTP下载文件的方法时,我们可以使用FtpWebRequest
类来执行FTP操作,并根据需要添加错误处理和重试机制。下面是一个示例代码:
cs
using System;
using System.IO;
using System.Net;
public class FTPDownloader
{
private const int MaxRetries = 3; // 最大重试次数
public bool DownloadFile(string ftpServer, string ftpUsername, string ftpPassword, string remoteFilePath, string localFilePath)
{
try
{
FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create($"{ftpServer}/{remoteFilePath}");
ftpRequest.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
using (FtpWebResponse ftpResponse = (FtpWebResponse)ftpRequest.GetResponse())
using (Stream stream = ftpResponse.GetResponseStream())
using (FileStream fileStream = File.Create(localFilePath))
{
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
{
fileStream.Write(buffer, 0, bytesRead);
}
}
Console.WriteLine($"Download succeeded: {remoteFilePath}");
return true;
}
catch (Exception ex)
{
// 处理异常
Console.WriteLine($"Error: {ex.Message}");
return false;
}
}
public bool DownloadFileWithRetry(string ftpServer, string ftpUsername, string ftpPassword, string remoteFilePath, string localFilePath)
{
int retries = 0;
bool success = false;
while (retries < MaxRetries && !success)
{
success = DownloadFile(ftpServer, ftpUsername, ftpPassword, remoteFilePath, localFilePath);
retries++;
if (!success)
{
Console.WriteLine("Download failed. Retrying...");
}
}
return success;
}
}
使用实例:
cs
string ftpServer = "ftp://example.com"; // FTP服务器地址
string ftpUsername = "username"; // FTP用户名
string ftpPassword = "password"; // FTP密码
string remoteFilePath = "file.txt"; // 远程文件路径
string localFilePath = "C:\\Download\\file.txt"; // 本地保存路径
FTPDownloader ftpDownloader = new FTPDownloader();
bool success = ftpDownloader.DownloadFileWithRetry(ftpServer, ftpUsername, ftpPassword, remoteFilePath, localFilePath);
if (success)
{
Console.WriteLine("File downloaded successfully.");
}
else
{
Console.WriteLine("Failed to download the file.");
}
在上述示例中,我们首先通过DownloadFile
方法执行FTP下载操作,并将远程文件保存到本地文件路径。如果下载失败,则在DownloadFileWithRetry
方法中进行最大重试次数的尝试,直到达到最大重试次数或下载成功为止。根据下载结果,可以在主程序中相应地处理成功或失败的情况。