【发布时间】:2014-03-05 22:51:56
【问题描述】:
我正在为大量文件运行此代码以通过 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);
}
}
【问题讨论】:
-
似乎可以通过吃异常的
catch语句的数量来判断一段代码sn-p的好坏。