gpt4 book ai didi

c# - 如何从 ftp 保存文件?

转载 作者:行者123 更新时间:2023-11-30 18:40:13 24 4
gpt4 key购买 nike

我有一个方法可以将文件夹结构从 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)

最佳答案

您应该尝试的第一件事是转 passive mode关闭,因为这会被大多数防火墙自动阻止,但这是 ftpWebRequest 的默认操作模式。

就在这条线的下面:

requestFileDownload.Method = WebRequestMethods.Ftp.DownloadFile;

还有这个:

requestFileDownload.UsePassive = false;

关于c# - 如何从 ftp 保存文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8644858/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com