550 error when attempting to upload file via FTP i

2019-08-01 13:11发布

问题:

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

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

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

回答1:

I had a very similar issue; for some reason using FtpWebRequest required me to use credentials for my FTP server with full access to all folders and subfolders, not just the folder I wanted to save to.

If I kept using the other credentials (which worked fine on other clients) I would repeatedly get the 550 error.

I would try another FTP user that has all access and see if that works.



回答2:

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


标签: c# .net ftp