12
我想从ftp服务器下载文件。 我已经写了下面的代码从FTP从ftp服务器下载文件时,“底层连接已关闭”
public void downloadFile(string FTPAddress, string filename, string username, string password, string destFile)
{
try
{
FtpWebRequest request = FtpWebRequest.Create(FTPAddress + filename) as FtpWebRequest;
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential(username, password);
request.UsePassive = true;
request.UseBinary = true;
request.UseBinary = true;
request.KeepAlive = false; //close the connection when done
request.Timeout = 60000;
//Streams
using (var response = request.GetResponse())
{
using (Stream reader = response.GetResponseStream())
{
byte[] buffer = new byte[1024];
using (Stream streamFile = File.Create(destFile))
{
while (true)
{
int bytesRead = reader.Read(buffer, 0, buffer.Length);
if (bytesRead == 0)
{
break;
}
else
{
streamFile.Write(buffer, 0, bytesRead);
}
}
}
}
}
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
}
下载文件,但运行此代码给我异常时:
基础连接已关闭: 发生意外的错误接收。
可以采取什么问题帮我...
当KeepAlive属性设置为false,当你调用Close方法控制连接被关闭。 在哪一行你会得到这个异常?您是否尝试使用Timeout属性(Infinity)的默认值? – Ofiris 2015-04-29 05:32:46
也许这是一个防火墙问题。您是否尝试过使用主动模式而不是被动模式? – Arjen 2015-04-29 08:19:27
这是您的服务器或本地tcp/ip问题(防火墙,防病毒等)的问题。代码工作正常,例如,这会在我的磁盘上创建一个ccrisconv.txt文件:'downloadFile(“ftp://ftp.nlm.nih.gov/”,“nlmdata/sample/ccris/ccrisconv.txt”,null ,null,“ccrisconv.txt”);' – 2015-04-30 16:07:05