Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# SFTP upload files

Tags:

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;     } 
like image 860
Eyal Avatar asked Nov 02 '14 15:11

Eyal


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is C full form?

Originally Answered: What is the full form of C ? C - Compiler . C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC PDP-11 computer in 1972.

How old is the letter C?

The letter c was applied by French orthographists in the 12th century to represent the sound ts in English, and this sound developed into the simpler sibilant s.

What is C language basics?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.


2 Answers

The best library/NuGet Package that I found was SSH.NET by Renci. Open up Nuget Package Manager and install this into your project.

The upload can be done with a stored file or a byte[] file.


Upload byte[] file

// you could pass the host, port, usr, and pass as parameters public void FileUploadSFTP() {     var host = "whateverthehostis.com";     var port = 22;     var username = "username";     var password = "passw0rd";          // http://stackoverflow.com/questions/18757097/writing-data-into-csv-file/39535867#39535867     byte[] csvFile = DownloadCSV(); // Function returns byte[] csv file      using (var client = new SftpClient(host, port, username, password))     {         client.Connect();         if (client.IsConnected)         {             Debug.WriteLine("I'm connected to the client");              using (var ms = new MemoryStream(csvFile))             {                 client.BufferSize = (uint)ms.Length; // bypass Payload error large files                 client.UploadFile(ms, GetListFileName());             }         }         else         {             Debug.WriteLine("I couldn't connect");         }     } } 

Upload From a Stored File

This was the site that I used as a resource to get me started: http://blog.deltacode.be/2012/01/05/uploading-a-file-using-sftp-in-c-sharp/

It's written for uploading files.

// you could pass the host, port, usr, pass, and uploadFile as parameters public void FileUploadSFTP() {     var host = "whateverthehostis.com";     var port = 22;     var username = "username";     var password = "passw0rd";      // path for file you want to upload     var uploadFile = @"c:yourfilegoeshere.txt";       using (var client = new SftpClient(host, port, username, password))     {         client.Connect();         if (client.IsConnected)         {             Debug.WriteLine("I'm connected to the client");              using (var fileStream = new FileStream(uploadFile, FileMode.Open))             {                                  client.BufferSize = 4 * 1024; // bypass Payload error large files                 client.UploadFile(fileStream, Path.GetFileName(uploadFile));             }         }         else         {             Debug.WriteLine("I couldn't connect");         }     } } 

Hopefully this is helpful for anyone trying to upload a file using SFTP in C#.

like image 193
Trevor Nestman Avatar answered Sep 17 '22 11:09

Trevor Nestman


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.

like image 27
Michael Armbruster Avatar answered Sep 19 '22 11:09

Michael Armbruster