我正在运行这个代码来传输许多文件,通过ftp本地传输到另一个服务器。问题是,我会周期性地遇到错误"远程服务器返回了一个错误: (421) 服务不可用,关闭控制连接"。是否有代码问题,或者更快更有效的传输文件的方法?所有文件都需要传输,所以我考虑使用 while 循环并捕获错误,直到文件夹中的所有文件都已传输。这是我遇到的周期性错误:
foreach (FileInfo file in files)
{
try
{
// Get the object used to communicate with the server.
FtpWebRequest request =
(FtpWebRequest)
WebRequest.Create(String.Format("{0}{1}/{2}", Host, destinationPath,
file.Name));
request.Method = WebRequestMethods.Ftp.UploadFile;
request.KeepAlive = false;
/* 20 mins timeout */
request.Timeout = 1200000;
request.ReadWriteTimeout = 1200000;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential(Username, Password);
// Copy the contents of the file to the request stream.
byte[] fileContents = File.ReadAllBytes(file.FullName);
request.ContentLength = fileContents.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(fileContents, 0, fileContents.Length);
}
//using (FtpWebResponse response = (FtpWebResponse) request.GetResponse())
//{
//}
if (deleteSourcePath)
{
File.Delete(file.FullName);
}
}
catch (Exception ex)
{
// Log.Warn("Error Moving Images", ex.Message);
}
}