Windows Forms Get Code Example
The following example demonstrates an SFTP session in a Windows Forms environment, in which a file is downloaded from the server. The session is executed asynchronously, without blocking the UI. The session is logged and progress is provided during the transfer.
< Back to all samples for PowerTCP SSH and SFTP for .NET
private void butGet_Click(object sender, System.EventArgs e)
{
//This application has a User-Interface, which we do not want to block.
//Start launches the specified method on a worker thread.
//Event handlers execute on the UI thread.
sftp1.Start(getFile, null);
}
private void getFile(object state)
{
//This function performs an SFTP Get operation using blocking calls.
//Use the Start method to execute this function on a worker thread.
try
{
//Connect and authenticate.
sftp1.Connection.RemoteEndPoint.HostNameOrAddress = "mySFtpServer";
sftp1.Connect();
sftp1.Authenticate("myUsername", "myPassword");
//Get the file and marshal the result back to the UI thread via the UserState event.
CopyResult result = sftp.Get("myFile.pdf", "c:\\MyFiles\\myFile.pdf", CopyMode.Copy);
sftp1.Marshal(result);
}
catch (Exception ex)
{
//Marshal exceptions to the UI thread via the Error event.
sftp1.Marshal(ex);
}
finally
{
//Logout and close the connection.
sftp1.Close();
}
}
private void sftp1_Progress(object sender, ProgressEventArgs e)
{
//Update a progress bar using information from the Progress event.
progressBar.Value = Convert.ToInt32(e.Progress.ByteCount * 100 / e.Progress.Size);
}
private void sftp1_Debug(object sender, DebugEventArgs e)
{
//Update a log with communication between the application and the server.
textLog.AppendText(e.Data.ToString());
}
private void sftp1_UserState(object sender, UserStateEventArgs e)
{
//This event is raised when a CopyResult is marshaled.
textLog.AppendText("Operation completed: " +
((CopyResult)e.UserState).Status.ToString() + "\r\n");
}
private void sftp1_Error(object sender, ComponentErrorEventArgs e)
{
//Update the log with any exceptions that occur.
textLog.AppendText("ERROR: " + e.GetException().Message + "\r\n");
}