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";
}
}