C#实现稳定的ftp下载文件方法

当使用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方法中进行最大重试次数的尝试,直到达到最大重试次数或下载成功为止。根据下载结果,可以在主程序中相应地处理成功或失败的情况。

相关推荐
吴_知遇24 分钟前
【华为OD机试真题】428、连续字母长度 | 机试真题+思路参考+代码解析(E卷)(C++)
开发语言·c++·华为od
basketball6161 小时前
Python torchvision.transforms 下常用图像处理方法
开发语言·图像处理·python
ABAP 成1 小时前
.NET Framework 4.0可用EXCEL导入至DataTable
c#
宁酱醇1 小时前
各种各样的bug合集
开发语言·笔记·python·gitlab·bug
啊吧怪不啊吧1 小时前
Linux常见指令介绍下(入门级)
linux·开发语言·centos
谷晓光1 小时前
Python 中 `r` 前缀:字符串处理的“防转义利器”
开发语言·python
Tiger Z1 小时前
R 语言科研绘图第 41 期 --- 桑基图-基础
开发语言·r语言·贴图
chuxinweihui1 小时前
数据结构——二叉树,堆
c语言·开发语言·数据结构·学习·算法·链表
陈大大陈2 小时前
基于 C++ 的用户认证系统开发:从注册登录到Redis 缓存优化
java·linux·开发语言·数据结构·c++·算法·缓存
看到我,请让我去学习2 小时前
C语言基础(day0424)
c语言·开发语言·数据结构