Search code examples
c#sshsftpsharpssh

How to move a file from one folder to another folder on a remote server using SharpSsh and C#


How to move a file from one folder to another folder on a remote server using SharpSsh?

I'm trying to move a file that is in a folder on the server to another server folder.

I'm getting:

ERROR: No se pudo encontrar el archivo '/local/opt/oracle/oradata/UTL_DIR/PEDIMENTOS/pedimento.csv'.

Cannot find file '/local/opt/oracle/oradata/UTL_DIR/PEDIMENTOS/pedimento.csv'

This is my code:

Tamir.SharpSsh.Sftp ClientSFTP = new Tamir.SharpSsh.Sftp(pHost, pUserName, pPassword);
try
{
    string FechaActual = DateTime.Today.ToString("yyyyMMdd");
    string pFilePEDIMENTOS = "/local/opt/oracle/oradata/UTL_DIR/PEDIMENTOS/pedimento.csv";
    string pFilePROCESADO = "/local/opt/oracle/oradata/UTL_DIR/PEDIMENTOS/PROCESADO/pedimento" + FechaActual + ".csv";

    //Abre sesion
    ClientSFTP.Connect();
   
    if (ClientSFTP.Connected)
    {
        // ejecutar el comando
        ClientSFTP.Put(pFilePEDIMENTOS, pFilePROCESADO);//SEGUIR INVESTIGANDO
    }
    else
    {
        throw new Exception("Error de Conexion con el Servidor Remoto");
    }
}
catch (Exception ex)
{
    lblError.Text = ex.Message;
}
finally
{
    //cerrar conexion SFTP
    ClientSFTP.Close();
}

Solution

  • First, do not use the SharpSSH, it's a dead project.

    Use another SFTP implementation. See SFTP Libraries for .NET.


    Anyway, if you have to use it (for a very good reason), use SftpChannel.rename method.

    You cannot use the Sftp class, as it does not expose the method.

    See jsch\examples\Sftp.cs example. A simplified code is like:

    Session session=jsch.getSession(pUserName, pHost, 22);
    ...
    session.connect();
    ...
    Channel channel=session.openChannel("sftp");
    ChannelSftp c=(ChannelSftp)channel;
    ...
    c.rename(pFilePEDIMENTOS, pFilePROCESADO);
    

    The "rename" or "move" are basically the same operations. The .Put is for uploading a local file to a remote location.