I have written a simple wrapper for WinSCP in C#. I have written it to simplify SFTP connections I will needing to perform.
public class WinSCPConn : IDisposable
{
//private fields
private SessionOptions sessionOptions;
private TransferOptions transferOptions;
private Session session;
//public properties
public bool IsSessionOpen { get { return session.Opened; } }
public WinSCPConn(string hostname, string username, string password)
{
sessionOptions = new SessionOptions();
sessionOptions.Protocol = Protocol.Sftp;
sessionOptions.HostName = hostname;
sessionOptions.PortNumber = 22;
sessionOptions.Password = password;
sessionOptions.UserName = username;
sessionOptions.Timeout = new TimeSpan(0, 3, 0);
sessionOptions.GiveUpSecurityAndAcceptAnySshHostKey = true;
transferOptions = new TransferOptions();
transferOptions.TransferMode = TransferMode.Binary;
try
{
session = new Session();
session.ExecutablePath = Properties.Settings.Default.WinSCPPath;
}
catch (SessionLocalException)
{
throw;
}
}
public void Open()
{
try
{
if (session.Opened == false)
{
session.Open(sessionOptions);
}
}
catch (SessionRemoteException)
{
throw;
}
}
public TransferOperationResult SendFile(string SourceFile, string DestFile)
{
TransferOperationResult result;
try
{
result = session.PutFiles(SourceFile, DestFile, false, transferOptions);
return result;
}
catch (SessionRemoteException)
{
throw;
}
}
public void CreateDirectory(string FolderPath)
{
try
{
if (!session.FileExists(FolderPath))
{
session.CreateDirectory(FolderPath);
}
}
catch (SessionRemoteException)
{
throw;
}
}
public void Close()
{
if (session.Opened == true)
{
session.Dispose();
}
}
public void Dispose()
{
Close();
}
}
It would be used as follows:
using (WinSCPConn conn = new WinSCPConn("host", "username", "password"))
{
conn.Open();
conn.CreateDirectory("/path/");
conn.SendFile(@"C:\file.txt","/path/file.txt");
}
My questions are as follows:
- How is my exception handling?
- Is there too much going on in the constructor?