Eyal Eyal - 4 months ago 121
C# Question

C# SFTP upload files

I am trying to upload files to a linux server but I am getting an error saying:
"

Unable to connect to the remote server
". I dont know if my code is wrong or the connection is blocked by the server - with the same details I can connect the server with FileZilla.

My code:

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

Answer

What you are trying to do here is to establish a FTPS connection which is not a SFTP connection. The EnableSsl option only activates FTP over TLS (so FTPS). It uses Port 21 to connect to the server.

If you really have activated SFTP in FileZilla, you have to use an SSH connection on port 22 to connect to the server (SFTP = SSH File Transfer Protocol). The easiest method to obtain this should be using SharpSSH.

You can also take a look into this question.

Comments