我正在尝试使用c#中的FTP从远程计算机下载文件,但是它不起作用。当我使用f10来使用GetResponse方法时,引发了异常。它说:“无法连接到远程服务器”,它看起来像是关于连接问题,但不是。
当我在ContentType和PreAuthenticate代码中创建请求时,抛出异常并说:“ System.NotSupportedException”
我该如何解决?有什么想法吗?
这是FTP的连接信息。
private static string host = @"ftp://XXX.XX.XXX.XX/";
private static string user = "XXXXXXXX";
private static string pass = "XXXXXXXX";
private static string localfile = @"E:/Files/Attachment";
private static string remoteFile = @"D:/log/stdlog.6.txt";
然后是FTP类
public class FtpServer
{
private string host = null;
private string user = null;
private string pass = null;
private FtpWebRequest ftpRequest = null;
private FtpWebResponse ftpResponse = null;
private Stream ftpStream = null;
private int bufferSize = 2048;
/* Construct Object */
public FtpServer(string hostIP, string userName, string password) { host = hostIP; user = userName; pass = password; }
public void Download(string remoteFile, string localFile)
{
try
{
ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host+remoteFile);
ftpRequest.Credentials = new NetworkCredential(user,pass);
ftpRequest.UseBinary = true;
ftpRequest.UsePassive = true;
ftpRequest.KeepAlive = true;
ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
ftpStream = ftpResponse.GetResponseStream();
FileStream localFileStream = new FileStream(localFile, FileMode.Create);
byte[] byteBuffer = new byte[bufferSize];
int bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
try
{
while (bytesRead > 0)
{
localFileStream.Write(byteBuffer, 0, bytesRead);
bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
localFileStream.Close();
ftpStream.Close();
ftpResponse.Close();
ftpRequest = null;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
return;
}
}
答案 0 :(得分:1)
无法连接到远程服务器可能有几个原因。
1),您可能会错误地键入服务器地址并指向不存在的地址。
2)服务器暂时关闭或关闭,您无法访问它。
3)您为服务器输入了错误的凭据。
无论哪种方式,我建议您在代码中实现using statement,而不要在每个流上使用close()
:
ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
using (ftpResponse = (FtpWebResponse)ftpRequest.GetResponse())
{
using (ftpStream = ftpResponse.GetResponseStream())
{
using (FileStream localFileStream = new FileStream(localFile, FileMode.Create))
{
byte[] byteBuffer = new byte[bufferSize];
int bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
try
{
while (bytesRead > 0)
{
localFileStream.Write(byteBuffer, 0, bytesRead);
bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}
ftpRequest = null;