要使用C# FluentFTP庫上傳文件,首先確保已經安裝了FluentFTP NuGet包。然后,按照以下步驟操作:
using System;
using System.IO;
using FluentFTP;
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();
if (!client.IsConnected)
{
Console.WriteLine("Failed to connect to FTP server.");
return;
}
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.");
}
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_host
、your_username
、your_password
和本地文件路徑。運行此代碼后,文件將從本地上傳到FTP服務器。