我尝试将文件上传到Linux服务器,但出现错误消息:无法连接到远程服务器
。我不知道是我的代码有问题还是连接被服务器阻止了。使用相同的详细信息,我可以通过FileZilla连接服务器。
我的代码:
const string UserName = "userName";
const string Password = "password";
const string ServerIp = "11.22.333.444/";
public bool UploadFile(HttpPostedFileBase file)
{
string fileName = file.FileName;
var serverUri = new Uri("ftp://" + ServerIp + fileName);
// the serverUri should start with the ftp:// scheme.
if (serverUri.Scheme != Uri.UriSchemeFtp)
return false;
try
{
// get the object used to communicate with the server.
var request = (FtpWebRequest)WebRequest.Create(serverUri);
request.EnableSsl = true;
request.UsePassive = true;
request.UseBinary = true;
request.Credentials = new NetworkCredential(UserName, Password);
request.Method = WebRequestMethods.Ftp.UploadFile;
// read file into byte array
var sourceStream = new StreamReader(file.InputStream);
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
// send bytes to server
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
var response = (FtpWebResponse)request.GetResponse();
Console.WriteLine("Response status: {0}", response.StatusDescription);
}
catch (Exception exc)
{
throw exc;
}
return true;
}