下面是一个基于C#的FTP文件上传功能的示例代码:

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

class FTPUploader
{
    public void UploadFile(string sourceFilePath, string destinationUrl, string username, string password)
    {
        try
        {
            // 创建FTP请求对象
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(destinationUrl);
            request.Method = WebRequestMethods.Ftp.UploadFile;

            // 设置FTP登录凭据
            request.Credentials = new NetworkCredential(username, password);

            // 读取本地文件
            using (Stream fileStream = File.OpenRead(sourceFilePath))
            {
                using (Stream ftpStream = request.GetRequestStream())
                {
                    // 将文件内容写入FTP上传流
                    byte[] buffer = new byte[1024];
                    int bytesRead = 0;
                    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        ftpStream.Write(buffer, 0, bytesRead);
                    }
                }
            }

            // 获取FTP服务器的响应
            using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
            {
                Console.WriteLine($"上传完成,状态:{response.StatusDescription}");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"上传失败,错误信息:{ex.Message}");
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        string sourceFilePath = "C:\\path\\to\\file.txt";
        string destinationUrl = "ftp://ftp.example.com/remote/file.txt";
        string username = "username";
        string password = "password";

        FTPUploader ftpUploader = new FTPUploader();
        ftpUploader.UploadFile(sourceFilePath, destinationUrl, username, password);
    }
}

请注意替换以下变量的值:

  • sourceFilePath:本地文件的路径
  • destinationUrl:FTP服务器上的目标路径和文件名
  • username:FTP服务器的用户名
  • password:FTP服务器的密码

这段代码将读取本地文件,并将其内容上传到指定的FTP服务器上。上传过程中将会显示上传状态。如果上传失败,将会显示错误信息

C#写一个FTP文件上传功能

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

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