Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
575 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The WinSCP .NET assembly supports providing the contents of a remote file using streams only in the current beta version (5.18), using the Session.GetFile method:

using (Stream stream = session.GetFile("/path/file.ext"))
{
    blockBlob.UploadFromStream(stream);
}

With the current stable version, all you can do, is to download the remote file to a local temporary location using the Session.GetFileToDirectory (or similar) and read the file from there:

// Download the remote file to the temporary location
var transfer = session.GetFileToDirectory("/path/file.ext", Path.GetTempPath());

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...