Search code examples
c#.netsftpssh.netsharpssh

How to append a text file on SFTP server using SharpSSH or SSH.NET library


I use Tamir.SharpSSH library to make my SFTP operations. I can upload file from client, delete or list files located in an SFTP server directory.

But I cannot find how to append a text file. I don't want to overwrite or delete the existing and upload a new one. I have a log file on that SFTP server. I have to add new lines to that file from client side.

I just searched the internet and looked different functions in the code but tried nothing to execute because I could not find anything till now.

Thanks in advance

EDIT

I decided to use Renci.SshNet library because of @Martin Prikryl's advise. I tried the above operations with that library also and I saw it works good. Also appending text to a text file is very simple with that library. I'm sharing a small example about that here:

using System
using Renci.SshNet;

namespace SFTPConnectSample
{
    class Program
    {
        static void Main(string[] args)
        {
            AppendText(@"/targetFolder/targetFile.txt");
        }

        private static void AppendText(string targetFilePath)
        {
            int portNumber = 22;

            using (SftpClient sftp = new SftpClient("myHostName", portNumber, "sftpUser", "sftpPassword"))
            {
                sftp.ConnectionInfo.Timeout = new TimeSpan(0, 0, 30);
                sftp.Connect();
                sftp.AppendAllText(targetFilePath, "\r\nThis is a new line for target text file.");
            }
        }
    }
}

Solution

  • First, do not use SharpSSH. It's an abandoned project, not updated for years.

    You can use SSH.NET library instead.

    Its SftpClient class has couple of methods you can use:

    public StreamWriter AppendText(string path)
    public void AppendAllText(string path, string contents)
    public void AppendAllLines(string path, IEnumerable<string> contents)
    

    If you must use SharpSSH for some reason, use:

    SftpChannel.get(fromFilePath, toFilePath, monitor, ChannelSftp.APPEND);