How to communicate with SFTP server

后端 未结 7 1694
谎友^
谎友^ 2021-02-14 01:48

I\'ve written a service for our customer that automatically transmits files to given destinations using FTP. For historic reasons I\'m using WinInet to perform the FTPing. All w

7条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-14 02:13

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


    You have to use a third party library for SFTP.

    You can use WinSCP .NET assembly. 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();
    }
    

    There are lot of other examples.


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


    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, somewhat for developing GUI applications, and not really for 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)


    Windows 10 also come with command-line OpenSSH sftp client. It can also be downloaded for older versions of Windows.

提交回复
热议问题