Reputation: 1283
I am trying to download only one file using SSH.NET from a server.
So far I have this:
using Renci.SshNet;
using Renci.SshNet.Common;
...
public void DownloadFile(string str_target_dir)
{
client.Connect();
if (client.IsConnected)
{
var files = client.ListDirectory(@"/home/xymon/data/hist");
foreach (SftpFile file in files)
{
if (file.FullName== @"/home/xymon/data/hist/allevents")
{
using (Stream fileStream = File.OpenWrite(Path.Combine(str_target_dir, file.Name)))
{
client.DownloadFile(file.FullName, fileStream);
}
}
}
}
else
{
throw new SshConnectionException(String.Format("Can not connect to {0}@{1}",username,host));
}
}
My problem is that I don't know how to construct the SftpFile
with the string @"/home/xymon/data/hist/allevents"
.
That's the reason, why I use the foreach
loop with the condition.
Thanks for the help.
Upvotes: 3
Views: 15863
Reputation: 41
If you want to check if the file exists, you can do something like that...
public void DownloadFile(string str_target_dir)
{
using (var client = new SftpClient(host, user, pass))
{
client.Connect();
var file = client.ListDirectory(_pacRemoteDirectory).FirstOrDefault(f => f.Name == "Name");
if (file != null)
{
using (Stream fileStream = File.OpenWrite(Path.Combine(str_target_dir, file.Name)))
{
client.DownloadFile(file.FullName, fileStream);
}
}
else
{
//...
}
}
}
Upvotes: 3
Reputation: 202272
You do not need the SftpFile
to call SftpClient.DownloadFile
. The method takes a plain path only:
/// <summary>
/// Downloads remote file specified by the path into the stream.
/// </summary>
public void DownloadFile(string path, Stream output, Action<ulong> downloadCallback = null)
Use it like:
using (Stream fileStream = File.OpenWrite(Path.Combine(str_target_dir, "allevents")))
{
client.DownloadFile("/home/xymon/data/hist/allevents", fileStream);
}
Had you really needed the SftpFile
, you could use SftpClient.Get
method:
/// <summary>
/// Gets reference to remote file or directory.
/// </summary>
public SftpFile Get(string path)
But you do not.
Upvotes: 3