0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

その6

Posted at
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)));
    }
}
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?