通过.Net从FTP下载文件,提示基础连接已经关闭: 服务器提交了协议冲突。很奇怪的是部分文件比如excel可以下载,部分文件又下载不了。在网上找了一圈,发现很多都说是中文的问题,我在config中的system.web下加入了
<globalization requestEncoding="utf-8" responseEncoding="utf-8" uiCulture="zh-CN" culture="zh-CN" fileEncoding="utf-8" />
还是没用,后来仔细找了下,发现是代码的问题,报错 的代码如下:
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.UsePassive = false;
reqFTP.Credentials = new NetworkCredential(ftpUser, ftpPassword);
using (FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse())
{
using (Stream ftpStream = response.GetResponseStream())
{
byte[] buffer = new byte[response.ContentLength];
ftpStream.Read(buffer, 0, buffer.Length);
return buffer;
}
}
换成以下代码即可解决问题:
using (WebClient wc = new WebClient())
{
wc.Credentials = new NetworkCredential(ftpUser, ftpPassword);
byte[] buffer = wc.DownloadData(url);
return buffer;
}