以下是一个使用.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文件路径,ftpUsernameftpPassword替换为FTP服务器的凭据,以及localFilePath替换为要保存下载文件的本地路径。然后,运行代码即可下载文件

net core 写一段页面FTP下载文件的代码

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

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