使用SSH.Net下载并返回非阻塞数据流 [英] Downloading and returning a non blocking stream of data using SSH.Net

查看:123
本文介绍了使用SSH.Net下载并返回非阻塞数据流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 ssh.net库来执行SFTP操作,以处理大型数据文件(> = 500MB )

I am using the ssh.net library for performing SFTP operations to work with large data files (>=500MB)

我在如何以非阻塞方式返回数据方面遇到问题.

I am having an issue with how to return the data in a non-blocking way.

ftpClient.DownloadFile()方法签名是可以的,当写入文件或可以通过某种方式实例化流时,但是当我想返回流而不阻塞时,如何使用它存在问题.

The ftpClient.DownloadFile() method signature is ok, when writing to a file or if there's some way I can instantiate the stream, but am having problems on how to use it when I want to return a stream without blocking.

到目前为止,我所看到的所有示例都将下载内容写入到Filestream中.没有什么可以返回流

All the examples I have seen so far will be writing the download to a Filestream. Nothing that just returns a stream

使用.Net的内置FTP,您只需使用response.GetResponseStream(),它就可以不阻塞地流回数据.

With .Net's built-in FTP, you just use response.GetResponseStream(), and it streams back the data, without blocking.

在return语句中使用它的唯一方法是写入临时文件.但这导致它是阻塞操作.

The only way round to using it in a return statement was writing to a temporarity file. But this results in it being a blocking operation.

        var tmpFilename = "temp.dat";
        int bufferSize = 4096;
        var sourceFile = "23-04-2015.dat";

        using (var stream = System.IO.File.Create(tmpFilename , bufferSize, System.IO.FileOptions.DeleteOnClose))
        {
            sftpClient.DownloadFile(sourceFile, stream);
            return stream;
        }

我不想阻止它,而是将其流回数据.

I don't want it to block but to stream back the data.

我也希望避免创建临时文件.

I also would like to avoid creating a temporary file.

是否有替代方法可以使它流回数据?

Is there an alternative implementation to make it stream back the data?

或者是否有我可以实例化的替代流(MemoryStream除外),该流适用于大文件?

Or is there an alternative stream I can instantiate(except for MemoryStream), that would work with large files?

推荐答案

这是个老问题,但我遇到了类似的问题. 如果要直接获取流,则可以写入MemoryStream.

This is old question, but I had similar issue. If you want to get the stream directly you can write to MemoryStream.

SftpClient _sftpClient;
_sftpClient = new SftpClient("sftp.server.domain", "MyLoginHere", "MyPasswordHere");
Stream fileBody = new MemoryStream();
_sftpClient.DownloadFile(ftpFile.FullName, fileBody);
fileBody.Position = 0; //dont forget to set the stream position back to beginning

如果要下载文件,可以将其放置在单独的线程中,也可以作为异步调用,然后调用委托:

If you want to download file, you can make it in separate thread or as asynchronous call and then call the delegate:

_sftpClient.DownloadFile(ftpFile.FullName, fileBody, YourActionDelegateHere);

这篇关于使用SSH.Net下载并返回非阻塞数据流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆