Donate

Append Text To Textfile In FTP Or SFTP Using SSH.NET

Hello,

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.
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! :)

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

Bootstrap Modal In ASP.NET MVC With CRUD Operations