远程服务器使用FtpWebRequest在上传文件上向FTP返回错误:(550)

时间:2017-10-05 08:06:03

标签: c# .net asp.net-mvc ftp ftpwebrequest

我需要通过ftp将文件上传到主机。在主机根目录上创建的/home2/travele2路径 enter image description here

我可以通过FileZilla程序将文件上传到主机,但是当我尝试通过网站上传文件时,它会出现这个错误:

  

远程服务器返回错误:(550)文件不可用(例如,找不到文件,无法访问)。

有什么问题?

// Get the object used to communicate with the server.  
FtpWebRequest ftpWebRequest = (FtpWebRequest)WebRequest.Create("ftp://00.00.00.00/home2/travele2");
ftpWebRequest.Method = WebRequestMethods.Ftp.UploadFile;
// This example assumes the FTP site uses anonymous logon.  
ftpWebRequest.Credentials = new NetworkCredential("aaaaaaa", "0000000");

// Copy the contents of the file to the request stream.  
StreamReader sourceStream = new StreamReader(Server.MapPath("/Content/Site.pdf"));
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
ftpWebRequest.ContentLength = fileContents.Length;

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

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

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

response.Close();

enter image description here

2 个答案:

答案 0 :(得分:3)

网址必须包含目标文件名:

FtpWebRequest ftpWebRequest =
    (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/home2/travele2/Site.pdf");

FtpWebRequest如何知道,使用什么名称?

一旦解决了这个问题,您就会发现上传会破坏文件,因为您将文件视为UTF-8编码的文本。什么是废话,因为PDF是二进制文件。

有关正确的代码,请参阅:
Upload and download a binary file to/from FTP server in C#/.NET

答案 1 :(得分:-1)

加载sourceStream的方式看起来有点可疑..我建议下载一个nuget库ftp客户端,它会让你的生活更轻松。 FluentFTP是一个很好的选择,有很好的文档和示例。

检查出来: https://github.com/robinrodricks/FluentFTP