ice*_*cub 16 .net c# ftp ftpwebrequest
一般信息
我还在学习C#.为了帮助自己,我正在尝试创建一个程序,它将自动将我的所有本地项目与我的FTP服务器上的文件夹同步.这样,无论我是在学校还是在家,我总是可以使用相同的项目.
我知道像Dropbox这样的程序已经为我做了这个,但我想创造类似的东西,我自己会教我很多东西.
问题
我迈向目标的第一步是从我的FTP服务器下载所有文件,子目录和子文件.我已经设法从下面的代码下载目录中的所有文件.但是,我的代码只列出了主目录中的文件夹名称和文件.子文件夹和子文件永远不会返回,也永远不会下载.除此之外,服务器返回550错误,因为我正在尝试下载文件夹,就像它们是文件一样.我已经在这上面了4个多小时了,但我找不到任何关于如何解决这些问题并让它发挥作用的事情.因此,我希望你们能帮助我:)
码
public string[] GetFileList()
{
string[] downloadFiles;
StringBuilder result = new StringBuilder();
WebResponse response = null;
StreamReader reader = null;
try
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);
request.UseBinary = true;
request.Method = WebRequestMethods.Ftp.ListDirectory;
request.Credentials = new NetworkCredential(ftpUserName, ftpPassWord);
request.KeepAlive = false;
request.UsePassive = false;
response = request.GetResponse();
reader = new StreamReader(response.GetResponseStream());
string line = reader.ReadLine();
while (line != null)
{
result.Append(line);
result.Append("\n");
line = reader.ReadLine();
}
result.Remove(result.ToString().LastIndexOf('\n'), 1);
return result.ToString().Split('\n');
}
catch (Exception ex)
{
if (reader != null)
{
reader.Close();
}
if (response != null)
{
response.Close();
}
downloadFiles = null;
return downloadFiles;
}
}
private void Download(string file)
{
try
{
string uri = url + "/" + file;
Uri serverUri = new Uri(uri);
if (serverUri.Scheme != Uri.UriSchemeFtp)
{
return;
}
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url + "/" + file);
request.UseBinary = true;
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential(ftpUserName, ftpPassWord);
request.KeepAlive = false;
request.UsePassive = false;
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
FileStream writeStream = new FileStream(localDestnDir + "\\" + file, FileMode.Create);
int Length = 2048;
Byte[] buffer = new Byte[Length];
int bytesRead = responseStream.Read(buffer, 0, Length);
while (bytesRead > 0)
{
writeStream.Write(buffer, 0, bytesRead);
bytesRead = responseStream.Read(buffer, 0, Length);
}
writeStream.Close();
response.Close();
}
catch (WebException wEx)
{
MessageBox.Show(wEx.Message, "Download Error");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Download Error");
}
}
Run Code Online (Sandbox Code Playgroud)
Mar*_*ryl 32
在FtpWebRequest没有递归文件操作(包括下载)任何明确的支持.你必须自己实现递归:
棘手的部分是识别子目录中的文件.用便携式方式无法做到这一点FtpWebRequest.该FtpWebRequest遗憾的是不支持的MLSD命令,这是检索目录列表中的FTP协议与文件属性的唯一可移植的方法.另请参阅检查FTP服务器上的对象是文件还是目录.
你的选择是:
LISTcommand = ListDirectoryDetailsmethod)并尝试解析特定于服务器的列表.许多FTP服务器使用*nix风格的列表,您可以d在条目的最开头通过它来标识目录.但是许多服务器使用不同的格式.以下示例使用此方法(假设为*nix格式)void DownloadFtpDirectory(string url, NetworkCredential credentials, string localPath)
{
FtpWebRequest listRequest = (FtpWebRequest)WebRequest.Create(url);
listRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
listRequest.Credentials = credentials;
List<string> lines = new List<string>();
using (FtpWebResponse listResponse = (FtpWebResponse)listRequest.GetResponse())
using (Stream listStream = listResponse.GetResponseStream())
using (StreamReader listReader = new StreamReader(listStream))
{
while (!listReader.EndOfStream)
{
lines.Add(listReader.ReadLine());
}
}
foreach (string line in lines)
{
string[] tokens =
line.Split(new[] { ' ' }, 9, StringSplitOptions.RemoveEmptyEntries);
string name = tokens[8];
string permissions = tokens[0];
string localFilePath = Path.Combine(localPath, name);
string fileUrl = url + name;
if (permissions[0] == 'd')
{
if (!Directory.Exists(localFilePath))
{
Directory.CreateDirectory(localFilePath);
}
DownloadFtpDirectory(fileUrl + "/", credentials, localFilePath);
}
else
{
FtpWebRequest downloadRequest = (FtpWebRequest)WebRequest.Create(fileUrl);
downloadRequest.Method = WebRequestMethods.Ftp.DownloadFile;
downloadRequest.Credentials = credentials;
using (FtpWebResponse downloadResponse =
(FtpWebResponse)downloadRequest.GetResponse())
using (Stream sourceStream = downloadResponse.GetResponseStream())
using (Stream targetStream = File.Create(localFilePath))
{
byte[] buffer = new byte[10240];
int read;
while ((read = sourceStream.Read(buffer, 0, buffer.Length)) > 0)
{
targetStream.Write(buffer, 0, read);
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
使用如下功能:
NetworkCredential credentials = new NetworkCredential("user", "mypassword");
string url = "ftp://ftp.example.com/directory/to/download/";
DownloadFtpDirectory(url, credentials, @"C:\target\directory");
Run Code Online (Sandbox Code Playgroud)
如果要避免解析特定于服务器的目录列表格式的麻烦,请使用支持该MLSD命令和/或解析各种LIST列表格式的第三方库; 和递归下载.
例如,使用WinSCP .NET程序集,只需一次调用即可下载整个目录Session.GetFiles:
// Setup session options
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.Ftp,
HostName = "ftp.example.com",
UserName = "user",
Password = "mypassword",
};
using (Session session = new Session())
{
// Connect
session.Open(sessionOptions);
// Download files
session.GetFiles("/directory/to/download/*", @"C:\target\directory\*").Check();
}
Run Code Online (Sandbox Code Playgroud)
在内部,MLSD如果服务器支持,WinSCP将使用该命令.如果没有,它使用该LIST命令并支持许多不同的列表格式.
默认情况下,该Session.GetFiles方法是递归的.
(我是WinSCP的作者)