The remote server returned an error: (550) on upload file to FTP using FtpWebRequest

The remote server returned an error: (550) on upload file to FTP using FtpWebRequest

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

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

The remote server returned an error: (550) File unavailable (e.g., file not found, no access).

有什么问题?

// 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();

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

查看: https://github.com/robinrodricks/FluentFTP

URL 必须包含目标文件名:

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

FtpWebRequest 要不然怎么知道,要用什么名字?


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

有关正确的代码,请参阅: