Access remote file contents as a stream using WinSCP .NET assembly

我的未来我决定 提交于 2020-01-10 03:05:07

问题


I am trying to open file to read from SFTP using WinSCP .NET assembly as par to my exercise to archive file from SFTP to Azure blob.

To upload a blob to Azure, I am using

using (var fileStream = inputStream)
{
    blockBlob.UploadFromStream(fileStream);
    blobUri = blockBlob.Uri.ToString();
}

How to get the stream from the file on SFTP server?

I managed using SftpClient to get the stream using the following code and it works but unfortunately not able to achieve the same using WinSCP .NET assembly.

sftpClient.OpenRead(file.FullName)

Can anyone help me how to achieve the same using WinSCP .NET assembly?

Because I need to connect to SFTP using username, password and privatekey I am using WinSCP .NET assembly.

Thanks


回答1:


The WinSCP .NET assembly Session API cannot not provide the contents of downloaded file using streams.

So all you can do, is to download the remote file to a local temporary location using the Session.GetFiles and read the file from there:

// Generate unique file name for the temporary file
string tempPath = Path.GetTempFileName();

// Download the remote file to the temporary location
session.GetFiles("/path/file.ext", tempPath).Check();

try
{
    // Open the temporarily downloaded file for reading
    using (Stream stream = File.OpenRead(tempPath))
    {
        // use the stream
        blockBlob.UploadFromStream(fileStream);
        blobUri = blockBlob.Uri.ToString();
    }
}
finally
{
    // Discard the temporarily downloaded file
    File.Delete(tempPath);
}


来源:https://stackoverflow.com/questions/33014313/access-remote-file-contents-as-a-stream-using-winscp-net-assembly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!