15

How to delete a file from a SFTP server using Tamir Gal's SharpSSH? I have been able to accomplish other functionality but deletion.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Joe Allen
  • 151
  • 1
  • 1
  • 3
  • A long belated follow-up for this question. I added this in a few updates that I did at https://bitbucket.org/mattgwagner/sharpssh to avoid re-compiling the library yourself. – MattGWagner Mar 12 '12 at 16:30

4 Answers4

24

The SshExec class didn't work for me, but a little Reflection magic worked:

var prop = sftp.GetType().GetProperty("SftpChannel", BindingFlags.NonPublic | BindingFlags.Instance);
var methodInfo = prop.GetGetMethod(true);
var sftpChannel = methodInfo.Invoke(sftp, null);
((ChannelSftp) sftpChannel).rm(ftpPath);
jbehren
  • 780
  • 6
  • 11
14

To accomplish this you will need to modify the SharpSSH assembly to expose the functionality you require.

Obtain the source code and open $\SharpSSH-1.1.1.13.src\SharpSSH\Sftp.cs

Insert the following lines of code before the end of the class:

public void Delete(string path)
{
    SftpChannel.rm(path);
}

Recompile and reference the recompiled DLL in your project. You will now be able to delete files on the SFTP server.

Matthew Sharpe
  • 3,667
  • 2
  • 25
  • 24
  • 3
    Thank you! Stumbled upon this and it works perfectly. Just another quick tip for anyone who wants to compile this themselves, it's helpful to use the following post-build ILMerge command to end up with one handy assembly called SharpSSH.dll: `ilmerge /target:library /out:"$(TargetDir)SharpSSH.dll" /v2 "$(TargetDir)Tamir.SharpSSH.dll" "$(TargetDir)DiffieHellman.dll" "$(TargetDir)Org.Mentalis.Security.dll"` – mattmc3 Oct 20 '10 at 13:02
  • Helped me too. Thank you so much!! – Vbp Aug 19 '13 at 20:33
6

Well you can also use SshExec class and then execute the "rm" command using "RunCommand" method. This way you wont have to recompile and build a new dll.

Ankur
  • 61
  • 1
  • 1
0

Using Tamir's dll I would suggest to delete using the below code. In this way, you need not modify Tamir's dll, whereas the below code can be written in your class.

string fromFile = "/a/b/MyFile.txt"
SshExec se = new SshExec(host, username, password);
se.Connect(port);
se.RunCommand("rm " + fromFile);
Sarath Subramanian
  • 20,027
  • 11
  • 82
  • 86