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;
}
}
}
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