我想要创建一个C#函数来测试到FTP服务器的连接。
这里是我的函数:
FtpWebRequest requestDir = (FtpWebRequest)FtpWebRequest.Create("ftp://" + strHost.Trim());
requestDir.Credentials = new NetworkCredential(strUser, strPass);
requestDir.Method = WebRequestMethods.Ftp.ListDirectory;
try
{
WebResponse response = requestDir.GetResponse();
return "ok";
}
catch (Exception ex)
{
return ex.Message;
}我的问题很简单:
我使用一个好主机(一个好的FTP主机),我的函数返回"OK“。如果在我使用坏主机之后,它返回一个异常
ERROR 421 : Service not available. Closing control connection.如果,atfer,它用好的代码重新测试,我将有一个新的时间--这个异常。
为了解决这个问题,我需要关闭并重新打开我的应用程序。
我试着:
KeepAlive = true / false and no changes.有人能帮我吗?
非常感谢,
诚挚的问候,
尼克修斯
发布于 2013-07-26 08:24:25
您应该使用FtpWebResponse类,并在获得目录清单后关闭它:
try
{
FtpWebResponse response = (FtpWebResponse)requestDir.GetResponse();
string status = response.StatusDescription;
response.Close();
return status;
}MSDN中的更多信息
注意:
对GetResponse的多次调用返回相同的响应对象;请求不会重新发出。
发布于 2013-08-01 07:38:19
在FtpWebResponse实现IDisposable接口时,您还可以这样使用它:
using (FtpWebResponse ftpWebResponse = (FtpWebResponse)requestDir.GetResponse())
{
...
}不需要显式调用close方法。
https://stackoverflow.com/questions/17570626
复制相似问题