here is a code sample i use:
class Processor : IDisposable
{
private string m_strTestBase = @"/Home/aaa/bbb";
private AsyncCallback m_asyncCallback = new AsyncCallback(CompleteDownload);
internal void Process()
{
....
m_sftpClient = new SftpClient("xxx", "yyy", "zzz");
m_sftpClient.Connect();
ProcessDirectory(m_strTestBase);
....
}
private static void CompleteDownload(IAsyncResult result)
class Processor : IDisposable
{
private class StateData
{
public Processor Processor { get; set; }
public FileStream FileStream { get; set; }
public string FileName { get; set; }
}
private SftpClient m_sftpClient;private string m_strTestBase = @"/Home/aaa/bbb";
private AsyncCallback m_asyncCallback = new AsyncCallback(CompleteDownload);
internal void Process()
{
....
m_sftpClient = new SftpClient("xxx", "yyy", "zzz");
m_sftpClient.Connect();
ProcessDirectory(m_strTestBase);
....
}
private static void CompleteDownload(IAsyncResult result)
{
SftpDownloadAsyncResult sftpDownloadAsyncResult = (SftpDownloadAsyncResult)result;
StateData stateData = (StateData)result.AsyncState;
Processor proc = stateData.Processor;
try
{
proc.m_sftpClient.EndDownloadFile(result);
Interlocked.Increment(ref proc.m_iDownloadedCnt);
// Write Console Output
Console.WriteLine("Success: " + stateData.FileName);
}
catch(Exception ex)
{
Interlocked.Increment(ref proc.m_iFailedCnt);
Console.WriteLine("Exception in 'CompleteDownload' [" + stateData.FileName + "]: " + ex.Message);
}
finally
{
try
{
stateData.FileStream.Flush();
stateData.FileStream.Dispose();
}
catch
{
}
if (Interlocked.Decrement(ref s_iRequestCounter) == 0)
{
proc.m_iEndProcessingEvent.Set();
}
}
}
private void ProcessFile(string strFile)
{
string str1 = strFile.Substring(m_strTestBase.Length + 1).Replace('/', '\\');
string strOutFileNameLong = Path.Combine(m_strTestOutputDataDir, str1);
if (!File.Exists(strOutFileNameLong))
{
string strOutDir = Path.GetDirectoryName(strOutFileNameLong);
if (!Directory.Exists(strOutDir))
{
Directory.CreateDirectory(strOutDir);
}
FileStream fs = File.Create(strOutFileNameLong, 4096, FileOptions.Asynchronous);
StateData stateData = new StateData { Processor = this, FileName = strOutFileNameLong, FileStream = fs };
Console.WriteLine("S: " + strFile + " --- D: " + strOutFileNameLong);
Interlocked.Increment(ref s_iRequestCounter);
m_sftpClient.BeginDownloadFile(strFile, fs, m_asyncCallback, stateData);
}
else
{
m_iSkippedCnt++;
}
}
private void ProcessDirectory(string strDirectory)
{
var vFiles = m_sftpClient.ListDirectory(strDirectory);
foreach (var vFile in vFiles)
{
if (vFile.IsDirectory)
{
ProcessDirectory(vFile.FullName);
}
else if (vFile.IsRegularFile)
{
ProcessFile(vFile.FullName);
}
}
}