当前位置: 代码网 > it编程>编程语言>Asp.net > C# SFTP客户端实现文件传输功能

C# SFTP客户端实现文件传输功能

2026年09月22日 Asp.net 我要评论
一、sftp信息ssh:加密的远程登陆/命令通道协议,可以链接到另一台机器执行命令,也可以传输一些文件;sftp:跑在ssh上面的文件传输协议,端口为22;ftp:1971年的明文传输协议,端口21,

一、sftp信息

ssh:加密的远程登陆/命令通道协议,可以链接到另一台机器执行命令,也可以传输一些文件;

sftp:跑在ssh上面的文件传输协议,端口为22;

ftp:1971年的明文传输协议,端口21,与sftp没有关系;

二、服务端openssh

1. systemctl enable --now ssh:开机自启 + 立即启动,启动的服务名为ssh.service

2. /etc/init.d/sshd start:运行sshd脚本,start为参数,还有stop啥的

3. ssh-keygen -a:生成密钥ssh_host_*_key,在服务端与客户端进行连接时,客户端发给服务端由它生成的公钥,服务端会留存这个公钥以识别openssh

4. /etc/ssh/sshd_config为ssh的配置文件,里面有端口、登陆账号(即linux账号)、密钥等;

三、客户端

1. 加载远程文件\目录列表

sftpclient client = new sftpclient(ip, port, username, password);  // 除了port为int外,其他参数都是string,用户名和密码是linux允许访问openssh账号名和密码,sshd_config allowuser那里做配置的
client.connect();
list<transfileinfo> entries = client.listdirectory(path)  // path服务端的路径
                                    .where(t => t.name != "." && t.name != ".." && !t.name.startswith('.'))  // 剔除"."当前目录、".."上级目录、"."开头的配置文件
                                    .orderbydescending(t => t.isdirectory)
                                    .thenby(t => t.name, stringcomparer.ordinalignorecase)
                                    .select(t => mew transfileinfo()
                                    {
                                        name = t.name,
                                        size = t.isdirectory ? 0 : t.length,
                                        time = t.lastwritetime.tostring("yyyy-mm-dd hh:mm"),
                                        isdirectory = t.isdirectory,
                                        fullpath = t.name
                                    });

2. 删除远程文件\目录

sftpclient client = new sftpclient(ip, port, username, password);
client.connect();  // sftpclient的创建和连接的成本很低,可以在每次执行时都创建并连接
sftpfileattributes attrs = client.getattributes(deletefilepath);
if (attrs.isdirectory)
    // 写个递归删除所有文件夹中的文件就行
else
    client.deletefile(deletefilepath);

3. 重命名

client.renamefile(oldfilepath, newpath);

4. 创建文件夹

client.createdirectory(dirpath);

5. 下载

long totallength = client.getattributes(remotepath).size;  // 获取一下远程文件的大小
string temppath = localpath + ".tmp";  // 先将远程文件保存至临时文件,结束后再删除掉.tmp后缀
long offset = 0;
if (file.exits(temppath))
{
    offset = (new fileinfo(temppath)).length;  // 因为提供的断点续传功能,所以临时文件的长度作为偏置,续传时就从这里开始
    if (offset >= totallength)
        offset = totallength;  // 偏置为totallength就算是下载完毕了
}

using stfpfilestream remotestream = client.openread(remotepath);
remotestream.seek(offset, seekorigin.begin);  // seekorigin.begin从文件开头开始偏移

using filestream localstream = new filestream(temppath, filemode.openorcreate, fileaccess.write, fileshare.none, 256 * 1024);  // 每次只读取256kb
localstream.seek(offset, seekorigin.begin);

byte[] buffer = new byte[256 * 1024];
while(true)
{
    if(!await check())
        continue;

    int read = await remotestream.readasync(buffer.asmemory(0, buffer.length));  // memory类似(指针 + 长度),由gc回收
    if (read == 0)
        break;

    await localstream.writeasync(buffer.asmemory(0, read));
}

// 回收流资源 + 复制临时文件
localstream.dispose();
if (file.exits(localpath))
    file.delete(localpath);

file.move(temppath, localpath);

async void check()
{
    taskcompletionsource<bool>? tcs;
    lock(_lock)
    {
        if (ispaused)
            return false;  // 这里省略了,ispaused为true时,while(true)那边不继续

        tcs = _pausetcs;
    }

    if (tcs != null)
        await tcs.task.configureawait(false);  // 在这里等
}

void resume()
{
    taskcompletionsource<bool>? tcs;
    lock(_lock)
    {
        if (!ispaused)
            return;

        ispaused = false;
        tcs = _pausetcs;
        _pausetcs = null;
    }

    tcs?.trysetresult(true);    
}

void cancel()
{
    taskcompletionsource<bool>? tcs;
    lock(_lock)
    {
        if (ispaused)
            return;

        ispaused = true;
        _pausetcs = new taskcompletionsource<bool>(taskcreationoptions.runcontinuationasynchronously);
    }

    tcs?.trysetresult(false);    
}

到此这篇关于c# sftp客户端实现文件传输功能的文章就介绍到这了,更多相关c# sftp客户端文件传输内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com