我正在运行此代码,以便通过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);
}
}
答案 0 :(得分:1)
在FtpWebResponse对象上调用Close。这将释放相关的端口。
FtpWebResponse response = (FtpWebResponse) request.GetResponse();
// ...
finally
{
if (response != null)
{
response.Close();
}
}