fadwa dhifi
fadwa dhifi

Reputation: 47

Delete lines from a file on Ubuntu server using SSH.NET

In the configuration file /etc/ssh/sshd_config I want to delete 4 lines starting from this line Match user sftpuser. I have developed the code below, The problem is the function SFTPCLient.WriteAllLines(string path, IEnumerable<string> contents); does not overwrite all the existing content, but if the new content is longer than the old, it substitutes the same bytes with the new once following by the rest.

SftpClient sftpClient = new SftpClient("xx.xxx.xxx.xxx", "root", "************");
sftpClient.Connect();
var newLines = new List<string>();
string[] oldlines = sftpClient.ReadAllLines("/sftp/sftpuser/test.txt");
int index = 0;
foreach(string line in oldlines)
{
    if (line.Equals("Match user sftpuser"))
                    {
                        break;
                    }
                    index++;
}

int[] indexdelete = { index, index + 1, index + 2, index + 3 };

for(int i =0; i < oldlines.Length; i++)
       {
                    if (indexdelete.Contains(i)) continue;
                    newLines.Add(oldlines[i]);            
        }         
sftpClient.WriteAllLines("/sftp/sftpuser/test.txt", newLines);
sftpClient.Disconnect();

Upvotes: 1

Views: 183

Answers (1)

Martin Prikryl
Martin Prikryl

Reputation: 202494

Indeed, that seems to be the way all SSH.NET SftpClient.WriteAll* methods are implemented – They do not erase the previous contents.

Use this code instead:

using (var writer = new StreamWriter(sftpClient.Create("/sftp/sftpuser/test.txt")))
{
    foreach (var line in newLines)
    {
        writer.WriteLine(line);
    }
}

Upvotes: 1

Related Questions