FTP连接失败“无法连接到远程服务器”

时间:2012-11-05 16:28:36

标签: c# ftpwebrequest

我正在尝试连接到FTP服务器以上传文件。我得到了“ 无法连接“错误。如果我使用命令行并打开FTP连接,我可以连接。不确定为什么在以编程方式连接时出现错误。任何帮助肯定会受到赞赏。

 FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://1.23.84.2");
 request.Method = WebRequestMethods.Ftp.UploadFile;                   

 request.Credentials = new NetworkCredential("user","password");

 // Copy the contents of the file to the request stream.    
 StreamReader sourceStream = new StreamReader(path);
 byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
 sourceStream.Close();
 request.ContentLength = fileContents.Length;

 Stream requestStream = request.GetRequestStream();
 requestStream.Write(fileContents, 0, fileContents.Length);
 requestStream.Close();

 FtpWebResponse response = (FtpWebResponse)request.GetResponse();

 Console.WriteLine("Upload File Complete, status {0}", 
          response.StatusDescription);

 response.Close();

2 个答案:

答案 0 :(得分:4)

因此,经过几个小时的故障排除后,McAfee正在阻止ftp端口。不得不暂时禁用本地计算机上的服务。

答案 1 :(得分:2)

我认为FtpWebReqest需要指向目标路径,而不仅仅是服务器的地址,如下所示:

FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://1.23.84.2/myFile.zip");

可以找到FtpWebRequest上下文中FTP上传的正确用法here