using Renci.SshNet;
using System;
using System.Collections.Generic;
using System.IO;
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 void Connect()
{
if (!sftpClient.IsConnected)
sftpClient.Connect();
}
public void Disconnect()
{
if (sftpClient.IsConnected)
sftpClient.Disconnect();
}
public void UploadFile(string localFilePath, string remoteFilePath)
{
try
{
using (var fileStream = new FileStream(localFilePath, FileMode.Open))
{
sftpClient.UploadFile(fileStream, remoteFilePath);
}
}
catch (Exception ex)
{
HandleSftpException(ex);
}
}
public void DownloadFile(string remoteFilePath, string localFilePath)
{
try
{
using (var fileStream = File.OpenWrite(localFilePath))
{
sftpClient.DownloadFile(remoteFilePath, fileStream);
}
}
catch (Exception ex)
{
HandleSftpException(ex);
}
}
public void DeleteFile(string remoteFilePath)
{
try
{
sftpClient.DeleteFile(remoteFilePath);
}
catch (Exception ex)
{
HandleSftpException(ex);
}
}
public void CreateDirectory(string remoteDirectoryPath)
{
try
{
sftpClient.CreateDirectory(remoteDirectoryPath);
}
catch (Exception ex)
{
HandleSftpException(ex);
}
}
public void DeleteDirectory(string remoteDirectoryPath)
{
try
{
sftpClient.DeleteDirectory(remoteDirectoryPath);
}
catch (Exception ex)
{
HandleSftpException(ex);
}
}
public IEnumerable<SftpFile> ListDirectory(string remoteDirectoryPath)
{
try
{
return sftpClient.ListDirectory(remoteDirectoryPath);
}
catch (Exception ex)
{
HandleSftpException(ex);
return null;
}
}
public bool IsConnected()
{
return 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