如何保存ftp文件?
本文关键字:ftp 文件 保存 何保存 | 更新日期: 2023-09-27 18:18:48
我有一个方法将文件夹结构从ftp复制到本地文件夹,然后复制其中包含的所有文件:
public void CreateDirectories()
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(Url);
request.Credentials = new NetworkCredential(Login, Pass);
request.Method = WebRequestMethods.Ftp.ListDirectory;
string soursePath = @"L:'Test";
StreamReader streamReader = new StreamReader(request.GetResponse().GetResponseStream());
string directoryName = streamReader.ReadLine();
while (directoryName != null)
{
//Create directories structure
if (directoryName.StartsWith("I") && !directoryName.Contains("p"))
{
string newPath = System.IO.Path.Combine(soursePath, directoryName);
if (!System.IO.Directory.Exists(newPath))
{
System.IO.Directory.CreateDirectory(newPath);
//get file list and invoke DownLoad(string directoryName, string fileName)
FtpWebRequest fileRequest = (FtpWebRequest)WebRequest.Create(Url + directoryName + "/");
fileRequest.Credentials = new NetworkCredential(Login, Pass);
fileRequest.Method = WebRequestMethods.Ftp.ListDirectory;
StreamReader fileStreamReader = new StreamReader(fileRequest.GetResponse().GetResponseStream());
string fileName = fileStreamReader.ReadLine();
while (fileName != null)
{
DownLoad(directoryName, fileName);
fileName = streamReader.ReadLine();
}
}
}
directoryName = streamReader.ReadLine();
}
request = null;
streamReader = null;
}
和复制当前文件的方法:
public void DownLoad(string directoryName, string fileName)
{
string localPath = @"L:'Test'" + directoryName;
FtpWebRequest requestFileDownload = (FtpWebRequest)WebRequest.Create("ftp://ftp.equip.me/prod/" + directoryName + "/" + fileName);
requestFileDownload.Credentials = new NetworkCredential(Login, Pass);
requestFileDownload.Method = WebRequestMethods.Ftp.DownloadFile;
FtpWebResponse responseFileDownload = (FtpWebResponse)requestFileDownload.GetResponse();
Stream responseStream = responseFileDownload.GetResponseStream();
FileStream writeStream = new FileStream(localPath + "''" + fileName, 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);
}
responseStream.Close();
writeStream.Close();
requestFileDownload = null;
responseFileDownload = null;
}
但是在Stream responseStream = responseFileDownload.GetResponseStream();它停止了近40秒,然后抛出一个超时异常,没有一个文件没有保存(文件很小- 50 kb)
您应该尝试的第一件事是关闭被动模式,因为这被大多数防火墙自动阻止,但这是ftpWebRequest的默认操作模式。
就在这行下面:
requestFileDownload.Method = WebRequestMethods.Ftp.DownloadFile;
和这个
requestFileDownload.UsePassive = false;