I have the following code to retrieve a file via FTP:
try
{
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);
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
using (Stream responseStream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(responseStream))
using (StreamWriter destination = new StreamWriter(destinationFile))
{
destination.Write(reader.ReadToEnd());
destination.Flush();
}
return 0;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
This works in most cases, but I have one client machine where I get an exception:
The remote server returned an error 403: Forbidden
Can anyone tell me why this could be the case开发者_开发知识库? It’s exactly the same code running on all clients (including the same username and password)?
I've encountered the same problem.
I have already done some monitoring. First I monitored communications for FTP connection via TotalCommander (It works, so it is a good reference). After that I also monitored my program. I was shocked by what was happening.
Somehow HTTP request was sent by an FTPRequest instance! I haven't solved the problem yet, but I am getting closer. I'll inform you if I find out anything new yet.
The solution was very simple for me. I just added the following line, after creating the request instance:
request.Proxy = null;
The only thing I can suggest is installing Wireshark and monitoring exactly what's being transmitted between the client and server, and comparing that between different machines. If necessary, to get the messages more similar between FTP and IE, change the request's user agent. Is there any funky networking going on, like IP-based permissions?
精彩评论