以下代码旨在通过FTP检索文件。 但是,我遇到了一个错误。
serverPath = "ftp://x.x.x.x/tmp/myfile.txt";
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverPath);
request.KeepAlive = true;
request.UsePassive = true;
request.UseBinary = true;
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential(username, password);
// Read the file from the server & write to destination
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) // Error here
using (Stream responseStream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(responseStream))
using (StreamWriter destination = new StreamWriter(destinationFile))
{
destination.Write(reader.ReadToEnd());
destination.Flush();
}
错误信息如下:
远程服务器返回了一个错误:(550)文件不可用(例如,文件未找到,无访问权限)
该文件在远程机器上确实存在,并且我能够手动执行ftp(即我拥有权限)。 请问为什么会出现这个错误?
WebClient
而不是FtpWebRequest
,您可以使用其DownloadFile
方法,而无需使用FileStream
进行繁琐的操作,这可能会更加容易。不过,WebClient 有一些做不到的事情(例如使用ACTV
而不是PASV
FTP:FtpWebRequest.UsePassive = false;
)。 - Owen Blacker