nRk
nRk

Reputation: 1239

SFTP with .NET 3.5

I need to connect to an SFTP server to download and upload files using C#/.NET 3.5.

Does the .NET 3.5 framework provide any built-in tools/mechanisms/libraries to connect to an SFTP server to download and upload files?

Upvotes: 3

Views: 11181

Answers (6)

Martin Prikryl
Martin Prikryl

Reputation: 202494

There's no support for SFTP in .NET framework, in any version.


The answer by Sanj shows how to use WinSCP by driving its console application. While that's indeed possible, where actually WinSCP .NET assembly that does it for a developer, giving him/her native .NET interface to the WinSCP scripting.

There's even a WinSCP NuGet package.

A trivial SFTP upload C# example:

// Setup session options
SessionOptions sessionOptions = new SessionOptions
{
    Protocol = Protocol.Sftp,
    HostName = "example.com",
    UserName = "user",
    Password = "mypassword",
    SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx...="
};

using (Session session = new Session())
{
    // Connect
    session.Open(sessionOptions);

    // Upload files
    session.PutFiles(@"d:\toupload\*", "/home/user/").Check();
}

And the same for VB.NET:

' Setup session options
Dim sessionOptions As New SessionOptions
With sessionOptions
    .Protocol = Protocol.Sftp
    .HostName = "example.com"
    .UserName = "user"
    .Password = "mypassword"
    .SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx...="
End With

Using session As New Session
    ' Connect
    session.Open(sessionOptions)

    ' Upload files
    session.PutFiles("d:\toupload\*", "/home/user/").Check()
End Using

There are lot of other examples in both languages (and more).


You can have WinSCP GUI generate an SFTP code template, like above, for you, including C#, VB.NET and PowerShell.

enter image description here


As mentioned above, the assembly is just a wrapper around WinSCP scripting, so it's not a completely native .NET code. As such it does not fit all use cases in .NET framework. It is mostly suitable for automating tasks, not for developing GUI or web applications.

For a fully native .NET SFTP library, see SSH.NET, which is strangely not mentioned in any answer yet.

(I'm the author of WinSCP)

Upvotes: 3

Sanj
Sanj

Reputation: 21

I prefer WinSCP. It's free and I've tried it before, it works perfectly. If you download the COM file and you could do something like below: NOTE: I'm passing the params from ini.

  const string logname = "log.xml";
            string username = ini.IniReadValue("sftp", "Username");
            string password = ini.IniReadValue("sftp", "Password");
            string remotehost = ini.IniReadValue("sftp", "Remote Host");
            string dloadpath = ini.IniReadValue("Download", "Local Path");

            Process winscp = new Process();
            winscp.StartInfo.FileName = @ini.IniReadValue("winscp", "compath");
            winscp.StartInfo.Arguments = "/log=" + logname;
            winscp.StartInfo.UseShellExecute = false;
            winscp.StartInfo.RedirectStandardInput = true;
            winscp.StartInfo.RedirectStandardOutput = true;
            winscp.StartInfo.CreateNoWindow = true;

            try
            {
                winscp.Start();
                lblconfirm.Text = "Status: WinSCP Started Successfully";
            }
            catch (Exception ex)
            {

                writeLog("from PutSFTP:  Could not run the WinSCP executable " + winscp.StartInfo.FileName + Environment.NewLine + ex.Message);
            }


            winscp.StandardInput.WriteLine("option batch abort");
            winscp.StandardInput.WriteLine("option confirm off");
            winscp.StandardInput.WriteLine("open sftp://" + username + ":" + password + "@" + remotehost);
            winscp.StandardInput.WriteLine("cd " + ini.IniReadValue("Download", "Remote Path"));
            winscp.StandardInput.WriteLine(@"get " + "/" + ini.IniReadValue("Download", "Remote Path") + "/*" + ini.IniReadValue("Download", "FileType") + " " + ini.IniReadValue("Download", "Local Path"));
            winscp.StandardInput.Close();

            string output = winscp.StandardOutput.ReadToEnd();
            lblconfirm.Text = "Download Success! Check logs for moe info";

            winscp.WaitForExit();

Upvotes: 1

Matt
Matt

Reputation: 27017

IIS 7.x (which comes with Windows server 2008 or Windows 7) supports only FTPs, not sFTP natively (explanation see update below) - however there are server solutions like this one available for the sFTP protocol.

If you require an sFTP client, Microsoft has not provided any support so far. But I've made very good expericence with a 3rd party .NET component named wodSFTP.NET, which is a sFTP client.

Here you can find the product & documentation: wodSFTP.NET. Examples and online-documentation can be downloaded without any charge or registration from them.

Note that you can choose whether you buy the version without or with Sourcecode in C#. They have a SSH component as well. Examples are always available (regardless of the version you choose) in C# and VB.NET.

Example (from the website www.weonlydo.com, converted to C#):

var wodSFTP1 = new WeOnlyDo.Client.SFTP();

// Authenticate with server using hostname, login, password.
wodSFTP1.Hostname = "your_hostname";
wodSFTP1.Login = "your_login";
wodSFTP1.Password = "your_password";
wodSFTP1.Blocking = True;  // Use synchronous connections
wodSFTP1.Connect();

wodSFTP1.GetFile("c:\", "/home/somepath/somefile.txt");

This example uses blocking (synchronous) mode. Note that you can also use the component asynchronously - in this case events will be fired and you can write event handlers to react on them.

Note that this example does not use a key to authenticate, but of course this is also supported (you can use key-based authentication, password-based authentication or both).


Update: FTPs and sFTP are different protocols. Please follow the links for an explanation.

Upvotes: 0

Nickolay Olshevsky
Nickolay Olshevsky

Reputation: 14160

Since there is no native support, uou can search in Google for other, commercial, components, just type something like 'SFTP components .NET'

Upvotes: -1

John Weldon
John Weldon

Reputation: 40789

The framework does not provide SFTP support.

Upvotes: 0

Tejs
Tejs

Reputation: 41256

No, .NET doesn't ship with any SFTP libraries. However, WinSCP is a free utility you can download. I've used it before to download information from a PayPal report server.

It has a nice command line setup for you to automate the download / upload of files too. So from my .NET app, you just invoke the process with the specific arguments and wait until it completes.

Upvotes: 1

Related Questions