C# FTP上传文件 FluentFTP

C# FTP上传文件 FluentFTP,程序可以正常上传文档,但是要自行添加容错机制,可能有时有上传不成功的,还在就是感谢上传的速度不理想,不用如 FileZilla Client效果好,后期改用Asp.net API 感谢效果不错,,能跑满服务器的最大带宽。

using FluentFTP;

using FluentFTP.Exceptions;

using FluentFTP.GnuTLS; //NuGet添加

private void StepUpload(ConfigInfo cfg)

{

string ftpHost = "yourServerIP";

string ftpUser = "yourName";

string ftpPwd = "yourPassword";

List fileList = new List();

foreach (var modelName in cfg.ModelNames)

{

for (int year = cfg.MinYear; year <= cfg.MaxYear; year++)

{

foreach (string folderName in new string[] { "xlsx", "docx", "pptx", "pdf", "png", "thumbnails", "images" })

{

string path = Path.Combine(cfg.OutputPath, $"Calendars\\{modelName}\\{folderName}\\{year}");

if (!Directory.Exists(path)) continue;

string[] files = Directory.GetFiles(path, "*.png", SearchOption.AllDirectories);

foreach (string file in files)

{

string targetFn = file.Replace(Path.Combine(cfg.OutputPath, "Calendars\\"), "");

fileList.Add(new FtpUploadItem { LocalPath = file, RemotePath = $"/upload/{targetFn}" });

}

}

}

}

try

{

using (var ftp = new FtpClient(ftpHost, ftpUser, ftpPwd))

{

ftp.Config.CustomStream = typeof(GnuTlsStream);

ftp.Config.EncryptionMode = FtpEncryptionMode.Explicit;

ftp.Config.DataConnectionEncryption = true;

ftp.Config.SslProtocols = SslProtocols.Tls12;

ftp.Config.ValidateAnyCertificate = true;

// 关闭TLS1.3,GnuTLS在部分环境有兼容性

// SslProtocols = SslProtocols.Tls12; //不要带Tls13

ftp.Config.SslProtocols = SslProtocols.Tls12;

ftp.Config.DataConnectionType = FtpDataConnectionType.AutoPassive;

ftp.Config.SslSessionLength = 0;

ftp.Connect();

progressBar.Minimum = 0;

progressBar.Maximum = fileList.Count;

progressBar.Value = 0;

foreach (var file in fileList)

{

this.Text = $"正在上传:{System.IO.Path.GetFileName(file.LocalPath)}";

progressBar.Value += 1;

//参数说明:本地路径,远程路径,覆盖,不自动创建目录,不校验

try

{

var status = ftp.UploadFile(file.LocalPath, file.RemotePath, FtpRemoteExists.Overwrite, true, FtpVerify.None);

if (status != FtpStatus.Success)

{

MessageBox.Show($"上传失败:{file.LocalPath}");

}

}

catch (FtpCommandException ftpEx)

{

// FTP协议层面错误(550权限、磁盘满等)

MessageBox.Show($"FTP命令异常:{ftpEx.Message}\r\n响应:{ftpEx.StackTrace}");

}

catch (Exception ex)

{

string msg = ex.Message;

if (ex.InnerException != null)

{

msg += $"\r\n内部异常:{ex.InnerException.Message}";

if (ex.InnerException.InnerException != null)

{

msg += $"\r\n深层内部:{ex.InnerException.InnerException.Message}";

}

}

MessageBox.Show(msg);

}

}

}

MessageBox.Show("全部上传完成");

}

catch (Exception ex)

{

MessageBox.Show($"FTP异常:{ex.Message}");

}

finally

{

this.Text = "Form1";

}

}

文件名精灵2025年最新版 机器翻译 AI智能
...
批量修改文件名称、文件夹名称

免费使用 功能无限制

全面接入机器自动翻译功能,主流AI大模型智能改名

方便快捷,支持正则表达式、无需安装功能齐全、支持定制无广告、无插件,放心使用。

点击下载 点击下载
本站中所有的计算器的计算结果仅供参考,本站对此结果的准确性不承担任何责任,实际数额以银行/保险公司/国家相关机构确认的结果为准。
在线客服QQ:543690914,备案号: 苏ICP备15037649号-27。东海县白塔埠镇佳诚电脑经营部版权所有。