【问题标题】:The remote server returned an error: (550) on upload file to FTP using FtpWebRequest远程服务器返回错误:(550) on upload file to FTP using FtpWebRequest
【发布时间】:2017-10-05 08:06:03
【问题描述】:

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

我可以通过 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();

【问题讨论】:

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


    【解决方案1】:

    URL 必须包含目标文件名:

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

    FtpWebRequest 怎么知道要使用什么名称?


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

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

    【讨论】:

      【解决方案2】:

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

      检查一下: https://github.com/robinrodricks/FluentFTP

      【讨论】:

      • 在推荐软件时,您应该明确说明您是否隶属于该项目。
      • 首先,它是一个开源库……不,我与这个项目没有任何关系。