自己也是个小白,程序简陋,不喜勿喷!
FTP弄了两天,只需要一个上传功能,也下了很多大佬的程序,太复杂,注释又少。连接成功后又各种问题,报错。
开发Visual Studio 2022,框架 .NET Framework 4.7.2
总结以下几点错误:
227(具体忘记了);500(具体忘记了);Timed out trying to connect(连接超时)
以下为具体步骤:
服务器FTP端
FTP帐号创建,FTP配置(腾讯云服务器,宝塔面板)
创建FTP帐号
修改FTP配置
取消以下两个的注释(删除 # )
PassivePortRange 39000 40000
ForcePassiveIP 82.0.0.0(此处为本服务器IP)
放行端口
1、腾讯云(两个放行,1、21FTP端口,2、39000-40000 PassivePortRange被动端口)
2、宝塔(安全)
代码端
安装 FluentFTP
点击项目,右键,按步骤安装
确保有这两个引用
代码
只有上传功能,下载和删除,可以自己根据代码修改,添加
using FluentFTP;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FTPvCESHI
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
string ftpServer = "ftp://82.0.0.0"; // FTP服务器地址,如果是SFTP,可能需要使用 sftp://
string userName = "vegas"; // FTP用户名
string password = "vegas123"; // FTP密码
int port = 21; // FTP端口,默认是21
string localFilePath = "2.txt";// 要上传的文件路径(此处为当前目录下的2.txt)
string remoteDirectory = "/vegas6/"; // 上传到FTP服务器的目录
string remoteFilePath = Path.Combine(remoteDirectory, Path.GetFileName(localFilePath)); // 完整的远程文件路径
// 创建FTP客户端实例
using (var ftp = new FtpClient(ftpServer, userName, password, port))
{
try
{
ftp.Connect();// 连接到FTP服务器
if (!ftp.DirectoryExists(remoteDirectory))
{
MessageBox.Show("目录不存在,已创建目录。");//判断个提示,可以删除 ftp.CreateDirectory(remoteDirectory);// 确保目标目录存在,如果不存在则创建
}
// 检查远程文件是否已存在,避免覆盖
if (ftp.FileExists(remoteFilePath))
{
MessageBox.Show("远程文件已存在,请选择其他文件名或覆盖现有文件。");
return; // 或者可以选择覆盖文件,取消下面的 return 语句
}
MessageBox.Show(localFilePath);
ftp.UploadFile(localFilePath, remoteFilePath);//上传文件
MessageBox.Show("文件上传成功!");
}
catch (Exception ex)
{
Console.WriteLine("发生异常:" + ex.Message);
// 检查 InnerException 是否有更详细的信息
if (ex.InnerException != null)
{
MessageBox.Show("内部异常信息:" + ex.InnerException.Message);
}
MessageBox.Show("上传文件时发生错误: " + ex.Message);
}
finally
{
// 断开FTP连接
if (ftp.IsConnected)
{
ftp.Disconnect();
}
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
窗体啥都没有
以上为全部内容
1、网上的不是不全,就是功能太复杂,对于新手小白太难(人生到处都是坑,没有真诚);
2、功能很简单,只是不懂配置,错误太多,找不到方法,始终过不了错误的砍(还是那句话思路很重要,偏了,怎么都对不了);
3、希望对新手有帮助,工程文件也会共享下载。富裕的支持下,不富裕的自己复制也是可以用。
点击富裕通道:https://download.youkuaiyun.com/download/q234579464573499/89077645