Tuesday, December 10, 2013

Append text to textfile in FTP or SFTP using SSH.NET

FtpWebRequest in .NET has few dozen bugs and some limitations when communicating to an FTP or perhaps an SFTP server. So, I decided to use SSH.NET which is a 3rd party .NET FTP client. You can use WinSCP or other existing FTP clients out there. Here's a sample code to append text to a textfile located in an FTP or SFTP Server.
Adding of reference:
 using Renci.SshNet;  
Append Text Method:
Code:
private void AppendTextToTextFile()  
     {  
       const int port = 22;  
       const string host = "192.168.2.1";  
       const string username = "greg";  
       const string password = "testpassword";  
       const string workingdirectory = "/root/files";  
       const string uploadfile = @"D:\uploadfile.txt";  
       Console.WriteLine("Creating client and connecting");  
       try  
       {  
         using (var client = new SftpClient(host, port, username, password))  
         {  
           client.Connect();  
           Console.WriteLine("Connected to {0}", host);            
           //add items to List<string> object  
           for (int i = 0; i < 5; i++)  
           {  
             dataToInsert.Add("test" + i);  
           }  
           //append text to file            
           using (StreamWriter writer = client.AppendText(workingdirectory + "/TestFile.txt"))  
           {  
             foreach (string data in dataToInsert)  
             {  
               byte[] writeData = Encoding.ASCII.GetBytes(data);  
               writer.WriteLine(data);  
             }    
           }  
         }  
       }  
       catch (Exception ex)  
       {  
         throw ex;  
       }  
     }  

Cheers! :)

0 comments:

Post a Comment