C#使用FTP发布文件或文件夹
一、选择一个已有的ftp站点,要求已知登录信息。如果没有,则本地添加ftp站点,具体添加ftp站点的教程如下,百度上有很多类似教程:
https://jingyan.baidu.com/article/dca1fa6f479469f1a4405292.html
二、选择正确的FTP操作库。可选择系统自带的FTP库,或者其他库如(推荐用FluentFTP,Nuget里可以下载到)
FluentFTP: https://www.nuget.org/packages/FluentFTP
三、具体代码
//用于验证登录信息是否正确
private bool validateLogin()
{
try
{
var Ip = tbxIp.Text;
var User = tbxUser.Text;
var Psw = tbxPwb.Password;
var uriStr = $"ftp://{Ip}";
var request = FtpWebRequest.Create(new Uri(_ftpPath));
request.Credentials = new NetworkCredential(_user, _password);
request.Method = WebRequestMethods.Ftp.ListDirectory;
var response = request.GetResponse();
response.Close();
request.Abort();
return true;
}
catch (Exception ex)
{
//没有登录上
}
return false;
}
//获取指定服务器路径下的文件/文件夹路径,此处的path应该是ftp://xxx.xxx.xxx.xx/ABC/DEF的文件夹路径
private List<string> GetFolders(string path)
{
var lstFolders = new List<string>();
try
{
var ftpGetFolders = (FtpWebRequest)WebRequest.Create(new Uri(path));
ftpGetFolders.Credentials = new NetworkCredential(_user, _password);
ftpGetFolders.Method = WebRequestMethods.Ftp.ListDirectoryDetails;//所有的文件列表,包括文件和文件夹
var response = ftpGetFolders.GetResponse();
var sReader = new StreamReader(response.GetResponseStream());//获取返回的字节流并解析
string line = sReader.ReadLine();
while (line != null)
{
if (line.Contains("<DIR>"))//所有的文件夹都有这个标志,但文件也有可能有这个命名,还是比较蛋疼的
{
string msg = line.Substring(line.LastIndexOf("<DIR>") + 5).Trim();
lstFolders.Add(msg);
}
line = sReader.ReadLine();
}
sReader.Close();
response.Close();
ftpGetFolders.Abort();
}
catch (Exception ex)
{
//ignore
}
return lstFolders;
}
//创建ftp文件夹,ftpFolderpath为以ftp://开头的文件夹完整路径
private bool CreateFolder(string ftpFolderpath)
{
try
{
var ftpMakeFolder = (FtpWebRequest)WebRequest.Create(new Uri(ftpFolderpath));
ftpMakeFolder.Credentials = new NetworkCredential(_user, _password);
ftpMakeFolder.Method = WebRequestMethods.Ftp.MakeDirectory;
var response = ftpMakeFolder.GetResponse();
response.Close();
ftpMakeFolder.Abort();
return true;
}
catch (Exception)
{//ignore
}
return false;
}
//发布文件,FilePath为本地的文件路径
private bool PublishFile(string FilePath)
{
try
{
var newPath = @"ftp://" + Ip + Loc + $"/{Path.GetFileName(FilePath)}";//发布的具体路径,详细到文件名
FtpWebRequest FTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(newPath));
FTP.Method = WebRequestMethods.Ftp.UploadFile;//选择上传文件方法
FTP.Credentials = new NetworkCredential(User, Psw);
var fs = new FileStream(FilePath, FileMode.Open);
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen = 0;
var strm = FTP.GetRequestStream();
WaitHelper.StartWaiting();
contentLen = fs.Read(buff, 0, buffLength);
while (contentLen != 0)
{
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}
strm.Close();
fs.Close();
WaitHelper.CloseWaiting();
FTP.Abort();
return true;
}
catch (Exception ex)
{
ControlUtility.ShowWarningMsgbox($"上传失败");
return false;
}
}
本文给出的只是一个基本操作,并没有做细节上的处理。FTP类中还有许多其他的方法有待学习。