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.

SFTP 非同期

0
Posted at
using Renci.SshNet;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;

public class SftpManager : IDisposable
{
    private SftpClient sftpClient;

    public SftpManager(string host, int port, string username, string privateKeyFilePath, string passphrase = null)
    {
        var privateKeyFile = new PrivateKeyFile(privateKeyFilePath, passphrase);
        var keyFiles = new[] { privateKeyFile };

        var connectionInfo = new ConnectionInfo(host, port, username, keyFiles);

        sftpClient = new SftpClient(connectionInfo);
    }

    public async Task ConnectAsync()
    {
        if (!sftpClient.IsConnected)
            await Task.Run(() => sftpClient.ConnectAsync());
    }

    public async Task DisconnectAsync()
    {
        if (sftpClient.IsConnected)
            await Task.Run(() => sftpClient.Disconnect());
    }

    public async Task UploadFileAsync(string localFilePath, string remoteFilePath)
    {
        try
        {
            using (var fileStream = new FileStream(localFilePath, FileMode.Open))
            {
                await Task.Run(() => sftpClient.UploadFile(fileStream, remoteFilePath));
            }
        }
        catch (Exception ex)
        {
            HandleSftpException(ex);
        }
    }

    public async Task DownloadFileAsync(string remoteFilePath, string localFilePath)
    {
        try
        {
            using (var fileStream = File.OpenWrite(localFilePath))
            {
                await Task.Run(() => sftpClient.DownloadFile(remoteFilePath, fileStream));
            }
        }
        catch (Exception ex)
        {
            HandleSftpException(ex);
        }
    }

    public async Task DeleteFileAsync(string remoteFilePath)
    {
        try
        {
            await Task.Run(() => sftpClient.DeleteFile(remoteFilePath));
        }
        catch (Exception ex)
        {
            HandleSftpException(ex);
        }
    }

    // 他のメソッドも同様に非同期メソッドに変更

    public async Task<bool> IsConnectedAsync()
    {
        return await Task.Run(() => sftpClient.IsConnected);
    }

    private void HandleSftpException(Exception ex)
    {
        Console.WriteLine($"SFTP Error: {ex.Message}");
    }

    public void Dispose()
    {
        if (sftpClient != null)
        {
            sftpClient.Dispose();
            sftpClient = null;
        }
    }
}
0
0
0

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?