using Renci.SshNet;
using System;
using System.IO;
class Program
{
static void Main()
{
string host = "SFTPホスト";
string username = "ユーザー名";
string privateKeyFilePath = "秘密鍵ファイルのパス";
int port = 22; // SFTPの通常のポートは22です
string remoteFilePath = "/リモートのファイルパス";
string localFilePath = "保存先のローカルファイルパス";
try
{
using (var client = new SftpClient(host, port, username, GetPrivateKey(privateKeyFilePath)))
{
client.Connect();
using (var fileStream = File.OpenWrite(localFilePath))
{
client.DownloadFile(remoteFilePath, fileStream);
}
client.Disconnect();
}
Console.WriteLine("ファイルをダウンロードしました。");
}
catch (Exception ex)
{
Console.WriteLine($"エラー: {ex.Message}");
}
}
static PrivateKeyFile GetPrivateKey(string privateKeyFilePath)
{
string privateKey = File.ReadAllText(privateKeyFilePath);
return new PrivateKeyFile(new MemoryStream(Encoding.UTF8.GetBytes(privateKey)));
}
}
More than 1 year has passed since last update.
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme