联通客户端访问电信服务器访问不了的解决方案:
访问FTP服务器有两种方式:port和passive,跨网络运营商访问FTP要使用:passive模式
设置ftp.UsePassive = true即可解决,我曾租用了阿里云的服务器ECS,是电信IP,电信用户正常访问,而联通用户就无法访问,总是报错,经过研究,发现就是这个ftp.UsePassive的问题,设置了ftp.UsePassive = true,但是还是无法访问,安全组中创建两个规则:20、21、1024-65535,详细看链接:
设置方法的链接1
设置方法的链接2
就能跨运营商访问FTP了!
public void DownloadFile(string localDir, string FtpDir, string FtpFile, string hostname, string username, string password)
{
string URI = "FTP://" + hostname + "/" + FtpDir + "/" + FtpFile;
//string URI = "FTP://" + hostname + "/" + FtpDir + FtpFile;
string tmpname = Guid.NewGuid().ToString();
string localfile = localDir + @"\" + tmpname;
System.Net.FtpWebRequest ftp = GetRequest(URI, username, password);
ftp.Method = System.Net.WebRequestMethods.Ftp.DownloadFile;
ftp.UseBinary = true;
ftp.UsePassive = true;
using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
//loop to read & write to file
using (FileStream fs = new FileStream(localfile, FileMode.CreateNew))
{
try
{
byte[] buffer = new byte[2048];
int read = 0;
do
{
read = responseStream.Read(buffer, 0, buffer.Length);
fs.Write(buffer, 0, read);
} while (!(read == 0));
responseStream.Close();
fs.Flush();
fs.Close();
}
catch (Exception)
{
//catch error and delete file only partially downloaded
fs.Close();
//delete target file as it's incomplete
File.Delete(localfile);
throw;
}
}
responseStream.Close();
}
response.Close();
}
try
{
File.Delete(localDir + @"\" + FtpFile);
File.Move(localfile, localDir + @"\" + FtpFile);
// ftp = null;
// ftp = GetRequest(URI, username, password);
ftp.Method = System.Net.WebRequestMethods.Ftp.DeleteFile;
// ftp.GetResponse();
}
catch (Exception ex)
{
File.Delete(localfile);
throw ex;
}
// 记录日志 "从" + URI.ToString() + "下载到" + localDir + @"\" + FtpFile + "成功." );
ftp = null;
}
秋风写于淄博,业务联系与技术交流QQ:375172665