c#连接SFTP上传文件

简介: 名词解释(百度百科) sftp是Secure File Transfer Protocol的缩写,安全文件传送协议。可以为传输文件提供一种安全的加密方法。sftp 与 ftp 有着几乎一样的语法和功能。

名词解释(百度百科)

sftp是Secure File Transfer Protocol的缩写,安全文件传送协议。可以为传输文件提供一种安全的加密方法。sftp 与 ftp 有着几乎一样的语法和功能。SFTP 为 SSH的一部份,是一种传输档案至 Blogger 伺服器的安全方式。其实在SSH软件包中,已经包含了一个叫作SFTP(Secure File Transfer Protocol)的安全文件传输子系统,SFTP本身没有单独的守护进程,它必须使用sshd守护进程(端口号默认是22)来完成相应的连接操作,所以从某种意义上来说,SFTP并不像一个服务器程序,而更像是一个客户端程序。SFTP同样是使用加密传输认证信息和传输的数据,所以,使用SFTP是非常安全的。但是,由于这种传输方式使用了加密/解密技术,所以传输效率比普通的FTP要低得多,如果您对网络安全性要求更高时,可以使用SFTP代替FTP。

代码实现:

1.添加引用 Renci.SshNet(通过Nuget下载)

https://www.nuget.org/packages/SSH.NET/2013.4.7

2.核心代码

const int port = 22; //端口
const string host = " "; //sftp地址
const string username = " "; //用户名
const string password = " ";//密码
const string workingdirectory = "/";//读取、上传文件的目录 "/"为根目录
const string uploadfile = @"c:\1.xml"; //上传文件地址

 
using (var client = new SftpClient(host, port, username, password)) //创建连接对象
{
client.Connect(); //连接
 

client.ChangeDirectory(workingdirectory); //切换目录
 

var listDirectory = client.ListDirectory(workingdirectory); //获取目录下所有文件
 
foreach (var fi in listDirectory) //遍历文件
{
Console.WriteLine(" - " + fi.Name);
// client.DeleteFile(fi.FullName);//删除文件
}

using (var fileStream = new FileStream(uploadfile, FileMode.Open))
{
client.BufferSize = 4 * 1024; // bypass Payload error large
client.UploadFile(fileStream, Path.GetFileName(uploadfile)); //上传文件
//UploadFile方法没有返回值,无法判断文件是否上传成功,我想到的解决办法是,上传后再获取一下文件列表,如果文件列表count比上传之前大,说明上传成功。当然
//这样的前提是只有你一个人上传。不知各位大神有没有其它办法
}
Console.ReadKey();

 

 完整示例:

/*
    get SSH.NET (BSD License: http://sshnet.codeplex.com/license)
    
    with NuGet:
    >Install-Package SSH.NET -Version 2013.4.7
    
    or just get the dll from here: http://j.mp/sshNet
    
*/
using System;
using System.Collections.Generic;
using Renci.SshNet; /* reference needed: Renci.SshNet.dll */

class Program
{
    static void Main(string[] args){

        // Setup Credentials and Server Information
        ConnectionInfo ConnNfo = new ConnectionInfo("hostOrIP",22,"username",
            new AuthenticationMethod[]{

                // Pasword based Authentication
                new PasswordAuthenticationMethod("username","password"),

                // Key Based Authentication (using keys in OpenSSH Format)
                new PrivateKeyAuthenticationMethod("username",new PrivateKeyFile[]{ 
                    new PrivateKeyFile(@"..\openssh.key","passphrase")
                }),
            }
        );

        // Execute a (SHELL) Command - prepare upload directory
        using (var sshclient = new SshClient(ConnNfo)){
            sshclient.Connect();
            using(var cmd = sshclient.CreateCommand("mkdir -p /tmp/uploadtest && chmod +rw /tmp/uploadtest")){
                cmd.Execute();
                Console.WriteLine("Command>" + cmd.CommandText);
                Console.WriteLine("Return Value = {0}", cmd.ExitStatus);
            }            
            sshclient.Disconnect();
        }

        // Upload A File
        using (var sftp = new SftpClient(ConnNfo)){
            string uploadfn = "Renci.SshNet.dll";

            sftp.Connect();
            sftp.ChangeDirectory("/tmp/uploadtest");
            using (var uplfileStream = System.IO.File.OpenRead(uploadfn)){
                sftp.UploadFile(uplfileStream, uploadfn, true);
            }
            sftp.Disconnect();
        }

        // Execute (SHELL) Commands
        using (var sshclient = new SshClient(ConnNfo)){
            sshclient.Connect();

            // quick way to use ist, but not best practice - SshCommand is not Disposed, ExitStatus not checked...
            Console.WriteLine(sshclient.CreateCommand("cd /tmp && ls -lah").Execute());
            Console.WriteLine(sshclient.CreateCommand("pwd").Execute());
            Console.WriteLine(sshclient.CreateCommand("cd /tmp/uploadtest && ls -lah").Execute());
            sshclient.Disconnect();
        }
        Console.ReadKey();
    }
}

 

目录
相关文章
|
4月前
|
C# 数据库
用C#连接到数据库实现学生学籍管理系统(二)
用C#连接到数据库实现学生学籍管理系统
|
5月前
|
SQL 关系型数据库 MySQL
C#使用Npgsql或SqlClient连接数据库
在C#使用Npgsql和SqlClient连接SQLserver、pgsql
64 2
|
7月前
|
SQL 关系型数据库 数据库连接
C#二十五 连接式访问数据库
C#二十五 连接式访问数据库
31 0
|
8月前
|
监控 安全 网络协议
Baumer工业相机堡盟相机如何通过BGAPI SDK获取相机的IP地址和相机连接的网口IP地址(C#)
Baumer工业相机堡盟相机如何通过BGAPI SDK获取相机的IP地址和相机连接的网口IP地址(C#)
90 0
|
8月前
|
存储 开发工具 C#
Baumer工业相机堡盟相机如何使用NEOAPI SDK实现相机的连接(C#)
Baumer工业相机堡盟相机如何使用NEOAPI SDK实现相机的连接(C#)
79 0
|
API C#
C#判断本机是否连接互联网
在日常开发中,我们可能遇到一些问题,需要判断电脑是否接入网络,从而来判断是否执行程序。
149 0
|
前端开发 关系型数据库 MySQL
【C#】【MySQL】C#连接MySQL数据库(二)解析
【C#】【MySQL】C#连接MySQL数据库(二)解析
165 0
|
C# 数据库
C#编程-65:连接数据库复习笔记
C#编程-65:连接数据库复习笔记
C#编程-65:连接数据库复习笔记
|
SQL 存储 程序员
C#连接数据库之Connection、Command、DataReader用法总结
C#连接数据库之Connection、Command、DataReader用法总结
301 0
C#连接数据库之Connection、Command、DataReader用法总结