Calling the method once after the connection is established is not useful - to prevent the connection from being closed by SSH-unfriendly routers along the way during no activity, you have to call it periodically (once every minute or two, for example).
For example, to add keep-alive functionality to
Sftp object, the following class could be used instead of the
/// Enhanced Sftp class which implements the keep-alive functionality.
/// Use this instead of Sftp in your code.
public class SftpKeepAlive : Sftp
// Timer object (needs to be referenced to prevent it from being
// claimed by the garbage collector).
private readonly System.Threading.Timer _keepAliveTimer;
// initialize the timer
var oneMinute = new TimeSpan(0, 1, 0);
_keepAliveTimer = new System.Threading.Timer(KeepAliveCallback, null, oneMinute, oneMinute);
private void KeepAliveCallback(object state)
if (State == SftpState.Ready)
// send keep-alive packet to the server
catch (Exception ex)
// log the exception here
(RFC 4253, which defines the
SSH_MSG_IGNORE message, states that it can be used as an additional protection measure against advanced traffic analysis techniques, but that's by no means the only usage. It has in fact been utilized as a simple keep-alive measure for years - check out http://www.sc.isc.tohoku.ac.jp/~hgot/sources/openssh-watchdog.html#others or http://www.chiark.greenend.org.uk/~sgtatham/putty/wishlist/two-way-keepalives.html).