+1 vote
by (290 points)

When I am trying to connect with SFTP server and if there is any exception then thrown SFTP execption does not contain error code matching with SFTP standard.

I have to handle all exception cases bases on error codes defined in SFTP standard.

How can I get the error code that represents SFTP error code?

Below is an example of exception data that is returned in case of connection closed.

        Code    UnknownError    Rebex.Net.SftpErrorCode
    [0] {[SftpStatus, ConnectionClosed]}    
    [1] {[Status, ConnectionClosed]}    
    Status  ConnectionClosed    Rebex.Net.SftpExceptionStatus
Applies to: Rebex SFTP

1 Answer

0 votes
by (148k points)

SFTP error codes are only available for SFTP protocol level errors that were reported by the server. This is indicated by SftpException's Status property of SftpExceptionStatus.ProtocolError. In this case, SFTP error code can be retrieved from SftpExceptions Code property.

Sample code:

try
{
    sftp.CreateDirectory(directoryPath);
}
catch (SftpException ex)
{
    if (ex.Status == SftpExceptionStatus.ProtocolError)
    {
        // SFTP protocol error => SFTP error code is available
        SftpErrorCode code = ex.Code;
        string message = ex.ProtocolMessage;
        ...
    }
    else
    {
        // not an SFTP protocol error => no SFTP error code
        throw;
    }
}

To get a numeric code value as defined by SFTP protocol drafts, convert SftpErrorCode value to an integer:

int nativeCode = (int)ex.Code;
by (290 points)
Even after trying multiple times I didn't get ex.Status == SftpExceptionStatus.ProtocolError
Instead everytime I get exception with message "Cannot perform requested operation in current session state." What this error message means?
by (148k points)
The "Cannot perform requested operation in current session state" error indicates that a method which has been called cannot be executed because the Sftp object's underlying SSH session is not in an appropriate state (no longer connected, for example). A log produced using Sftp object's LogWriter property (as described at https://rebex.net/kb/logging/) should make it possible to tell what exactly went wrong.
...