c# fluentftp如何上传文件

c#
639
2024/11/21 12:31:44
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

要使用C# FluentFTP库上传文件,首先确保已经安装了FluentFTP NuGet包。然后,按照以下步骤操作:

  1. 引入必要的命名空间:
using System;
using System.IO;
using FluentFTP;
  1. 创建一个FtpClient对象并连接到FTP服务器:
string host = "your_ftp_host";
int port = 21; // 默认的FTP端口是21
string username = "your_username";
string password = "your_password";

FtpClient client = new FtpClient(host, port, username, password);
client.EncryptionMode = FtpEncryptionMode.Explicit; // 设置加密模式为显式
client.Connect();
  1. 检查连接是否成功:
if (!client.IsConnected)
{
    Console.WriteLine("Failed to connect to FTP server.");
    return;
}
  1. 使用UploadFile方法上传文件:
string localFilePath = @"C:\path\to\your\local\file.txt"; // 本地文件路径
string remoteFilePath = "/remote/path/file.txt"; // FTP服务器上的目标路径

bool success = client.UploadFile(localFilePath, remoteFilePath);

if (success)
{
    Console.WriteLine("File uploaded successfully.");
}
else
{
    Console.WriteLine("Failed to upload file.");
}
  1. 断开与FTP服务器的连接:
client.Disconnect();

完整的示例代码如下:

using System;
using System.IO;
using FluentFTP;

namespace FtpUploadExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string host = "your_ftp_host";
            int port = 21;
            string username = "your_username";
            string password = "your_password";

            FtpClient client = new FtpClient(host, port, username, password);
            client.EncryptionMode = FtpEncryptionMode.Explicit;
            client.Connect();

            if (!client.IsConnected)
            {
                Console.WriteLine("Failed to connect to FTP server.");
                return;
            }

            string localFilePath = @"C:\path\to\your\local\file.txt";
            string remoteFilePath = "/remote/path/file.txt";

            bool success = client.UploadFile(localFilePath, remoteFilePath);

            if (success)
            {
                Console.WriteLine("File uploaded successfully.");
            }
            else
            {
                Console.WriteLine("Failed to upload file.");
            }

            client.Disconnect();
        }
    }
}

请根据实际情况替换your_ftp_hostyour_usernameyour_password和本地文件路径。运行此代码后,文件将从本地上传到FTP服务器。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: c# listviewitem是否支持虚拟模式