当对我们的内部网络中的服务器运行下面的代码工作。 当我更改凭据,以反映我们的网络外部的服务器,我得到一个550错误响应。 当我捕捉到了异常,如下所示:
try {
requestStream = request.GetRequestStream();
FtpWebResponse resp = (FtpWebResponse)request.GetResponse();
}
catch(WebException e) {
string status = ((FtpWebResponse)e.Response).StatusDescription;
throw e;
}
状态的数值为:“550命令STOR失败\ 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();
}
}