尝试通过远程服务器上的 C# 中的 FTP 上传文件时出现 550 错误

550 error when attempting to upload file via FTP in C# on remote server

以下代码在 运行 针对我们内部网络中的服务器时有效。当我更改凭据以反映我们网络外部的服务器时,我收到 550 错误响应。当我像这样捕获异常时:

try { 
    requestStream = request.GetRequestStream();
    FtpWebResponse resp = (FtpWebResponse)request.GetResponse();

}
catch(WebException e) {
    string status = ((FtpWebResponse)e.Response).StatusDescription;
    throw e;
}

status 的值为: “550 命令 STOR failed\r\n”

我可以使用 Filezilla 等客户端使用相同的凭据成功上传文件。我已经尝试使用 SetMethodRequiresCWD() 作为其他答案的建议,但这对我不起作用。

这是代码,它接收一个字符串列表,每个字符串都包含一个文件的完整路径。

private void sendFilesViaFTP(List<string> fileNames) {
    FtpWebRequest request = null;

    string ftpEndPoint = "ftp://pathToServer/";
    string fileNameOnly; //no path
    Stream requestStream;

    foreach(string each in fileNames){
        fileNameOnly = each.Substring(each.LastIndexOf('\') + 1);

        request = (FtpWebRequest)WebRequest.Create(ftpEndPoint + fileNameOnly);
        request.Method = WebRequestMethods.Ftp.UploadFile;

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

        StreamReader fileToSend = new StreamReader(each);

        byte[] fileContents = Encoding.UTF8.GetBytes(fileToSend.ReadToEnd()); //this is assuming the files are UTF-8 encoded, need to confirm
        fileToSend.Close();
        request.ContentLength = fileContents.Length;

        requestStream = request.GetRequestStream();


        requestStream.Write(fileContents, 0, fileContents.Length);
        requestStream.Close();

        FtpWebResponse response = (FtpWebResponse)request.GetResponse(); //validate this in some way?
        response.Close();
    }
}

我有一个非常相似的问题;出于某种原因,使用 FtpWebRequest 要求我使用我的 FTP 服务器的凭据 完全访问所有文件夹和子文件夹 ,而不仅仅是我想保存到的文件夹.

如果我继续使用其他凭据(在其他客户端上运行良好),我会反复收到 550 错误。

我会尝试另一个具有所有访问权限的 FTP 用户,看看是否可行。

我无法使用 FtpWebRequest 解决此问题。我使用 WebClient 重新实现如下,它产生了更简洁的代码并且有工作的附带好处:

    private void sendFilesViaFTP(List<string> fileNames){
        WebClient client = new WebClient();
        client.Credentials = new NetworkCredential("username", "password");
        foreach(string each in fileNames){
            byte[] response = client.UploadFile("ftp://endpoint/" + each, "STOR", each);
            string result = System.Text.Encoding.ASCII.GetString(response);
            Console.Write(result);
        }
    }