以下是一个使用 .NET Core 编写的简单示例代码,用于从 FTP 服务器下载文件:

using System;
using System.IO;
using System.Net;

namespace FTPDownloadExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string ftpUrl = 'ftp://example.com/file.txt';
            string ftpUsername = 'username';
            string ftpPassword = 'password';
            string localFilePath = 'C:\Downloads\file.txt';

            try
            {
                // 创建 FTP 请求对象
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpUrl);
                request.Method = WebRequestMethods.Ftp.DownloadFile;
                request.Credentials = new NetworkCredential(ftpUsername, ftpPassword);

                // 发送 FTP 请求并获取响应
                FtpWebResponse response = (FtpWebResponse)request.GetResponse();

                // 打开本地文件用于写入
                using (Stream responseStream = response.GetResponseStream())
                using (FileStream fileStream = new FileStream(localFilePath, FileMode.Create))
                {
                    // 从 FTP 响应流中读取数据并写入本地文件
                    byte[] buffer = new byte[1024];
                    int bytesRead;
                    while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        fileStream.Write(buffer, 0, bytesRead);
                    }
                }

                Console.WriteLine('文件下载完成');
            }
            catch (Exception ex)
            {
                Console.WriteLine($'发生错误: {ex.Message}');
            }
        }
    }
}

在上述代码中,你需要将 'ftpUrl' 替换为实际的 FTP 文件路径,'ftpUsername' 和 'ftpPassword' 替换为 FTP 服务器的凭据,以及 'localFilePath' 替换为要保存下载文件的本地路径。然后,运行代码即可下载文件。

.NET Core FTP 下载文件代码示例

原文地址: https://www.cveoy.top/t/topic/qx5q 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录