c# - 远程服务器返回错误 : (550) on upload file to FTP using FtpWebRequest

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

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

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

enter image description here

最佳答案

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

关于c# - 远程服务器返回错误 : (550) on upload file to FTP using FtpWebRequest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46580751/

相关文章:

c# - 如何按名称扫描并杀死进程

.net - Process.Start() 不适用于 Windows 2012 R2

c# - 控件中的嵌入窗体或作为用户控件的窗体

javascript - 使用 Partial View 作为带有变量的可重用 html 代码

css - ASP.NET Web 表单动态更改 Bootstrap 主题

c# - 在主线程中捕获异步异常

c# - 帮助搜索引擎架构 .NET C#

c# - 在 Web 应用程序中设置 WCF TCP 服务

c# - .NET 2/3 应用程序拒绝在 .NET 4 下运行

asp.net-mvc - ASP.NET MVC 5应用程序的LinkedIn登录