public bool UploadToSFTP(MemoryStream ms, string filename, bool overwrite)
{
string strPath = sshPath;
if (!strPath.StartsWith("/")) {
strPath = "/" + strPath;
}
if (!strPath.EndsWith("/")) {
strPath += "/";
}
bool bRet = true;
bool bWait = true;
sshError = "";
if (sshConnection == null || !sshConnection.IsConnected) {
bool bResume = false;
bool bOK = false;
connectionDoneCallback = (bool bSuccess) => {
bOK = bSuccess;
bResume = true;
};
Connect();
while (!bResume) System.Threading.Thread.Sleep(1);
if (!bOK) {
sshError = "Couldn't connect to server.";
return false;
}
}
try {
this.ProgressBar.Start(filename, ms.Length);
ms.Seek(0, SeekOrigin.Begin);
IAsyncResult arUpload = null;
AsyncCallback cbFinished = (IAsyncResult ar) => {
bRet = true;
bWait = false;
};
Action<ulong> cbProgress = new Action<ulong>((ulong offset) => {
this.ProgressBar.Set((long)offset);
if (this.ProgressBar.Canceled) {
sshConnection.EndUploadFile(arUpload);
bRet = false;
bWait = false;
}
});
try {
arUpload = sshConnection.BeginUploadFile(ms, strPath + filename, overwrite, cbFinished, filename, cbProgress);
} catch {
// failed to upload, queue it for a retry after reconnecting
sshConnection = null;
connectionDoneCallback = (bool bSuccess) => {
if (!bSuccess) {
bRet = false;
sshError = "Upload failed because couldn't connect to server.";
bWait = false;
return;
}
try {
arUpload = sshConnection.BeginUploadFile(ms, strPath + filename, overwrite, cbFinished, filename, cbProgress);
} catch (Exception ex) {
bRet = false;
sshError = "Upload failed twice: " + (ex.InnerException != null ? ex.InnerException.Message : ex.Message);
bWait = false;
}
};
Connect();
}
} catch (Exception ex) {
bRet = false;
bWait = false;
sshError = ex.InnerException != null ? ex.InnerException.Message : ex.Message;
throw ex;
}
while (bWait) System.Threading.Thread.Sleep(1);
this.ProgressBar.Done();
return bRet;
}