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

问题描述:

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

The below code works when run against a server in our internal network. When I change the credentials to reflect a server outside of our network, I get a 550 error in response. When I catch the exception like so:

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

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

状态的值为: "550命令STOR失败\ r \ n"

status has a value of: "550 Command STOR failed\r\n"

我可以使用客户端(例如Filezilla)使用相同的凭据成功上传文件.我已经尝试过使用SetMethodRequiresCWD(),如其他答案所建议的那样,这对我不起作用.

I can successfully upload a file using the same credentials using a client such as Filezilla. I have already tried using SetMethodRequiresCWD() as other answers have suggested and this did not work for me.

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

Here is the code, which receives a list of strings that each contain a full path to a file.

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解决此问题.我使用如下所示的WebClient重新实现,它生成了更简洁的代码,并具有工作的好处:

I was not able to resolve this using FtpWebRequest. I re-implemented using WebClient as below, which produced more concise code and had the side-benefit of working:

    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);
        }
    }