This commit is contained in:
PastSaid
2024-07-16 10:33:50 +08:00
parent e8a1f46c3d
commit fa480006a8
132 changed files with 20893 additions and 4519 deletions

View File

@@ -1,10 +1,12 @@
using Renci.SshNet;
using Renci.SshNet.Sftp;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using static System.Collections.Specialized.BitVector32;
namespace HandleUtils
{
@@ -29,9 +31,9 @@ namespace HandleUtils
/// <param name="port">端口</param>
/// <param name="user">用户名</param>
/// <param name="pwd">密码</param>
public SFTPHelper(string ip, string user, string pwd, string port = "22")
public SFTPHelper(string ip, string user, string pwd, int port = 22)
{
_sftp = new SftpClient(ip, int.Parse(port), user, pwd);
_sftp = new SftpClient(ip, port, user, pwd);
Connect();
}
@@ -89,14 +91,14 @@ namespace HandleUtils
/// </summary>
/// <param name="localPath">本地路径</param>
/// <param name="remotePath">远程路径</param>
public void Put(string localPath, string remotePath)
public void Put(string localPath, string remotePath, Action<ulong> action = null)
{
try
{
using (var file = File.OpenRead(localPath))
{
Connect();
_sftp.UploadFile(file, remotePath);
_sftp.UploadFile(file, remotePath, action);
}
}
catch (Exception ex)
@@ -136,8 +138,70 @@ namespace HandleUtils
}
}
/// <summary>
/// 获取全部文件
/// </summary>
/// <param name="remotePath"></param>
/// <param name="localPath"></param>
/// <exception cref="Exception"></exception>
public void Mget(string remotePath, string localPath, Func<List<string>, bool> action = null)
{
try
{
Connect();
var files = _sftp.ListDirectory(remotePath);
var result = new List<string>();
foreach (var file in files)
{
using (var fs = File.OpenWrite(localPath + file.Name))
{
result.Add(file.Name);
_sftp.DownloadFile(file.FullName, fs);
}
}
action?.Invoke(result);
}
catch (Exception ex)
{
throw new Exception(string.Format("SFTP文件获取失败原因{0}", ex.Message));
}
finally
{
Disconnect();
}
}
/// <summary>
/// 下载文件
/// </summary>
/// <param name="remotePath"></param>
/// <param name="localPath"></param>
/// <exception cref="Exception"></exception>
public void DownloadFile(string remotePath, string localPath, Action<ulong> action = null)
{
try
{
Connect();
using (var fs = File.OpenWrite(localPath))
{
_sftp.DownloadFile(remotePath, fs, action);
}
}
catch (Exception ex)
{
throw new Exception(string.Format("SFTP下载文件失败原因{0}", ex.Message));
}
finally
{
Disconnect();
}
}
#endregion
#region SFTP文件
/// <summary>
/// 重命名SFTP文件
@@ -188,6 +252,29 @@ namespace HandleUtils
#endregion
#region SFTP文件列表
/// <summary>
/// 获取SFTP文件列表
/// </summary>
/// <param name="remotePath">远程目录</param>
/// <returns></returns>
public List<SftpFile> GetFileList(string remotePath)
{
try
{
var files = _sftp.ListDirectory(remotePath);
return files.ToList();
}
catch (Exception ex)
{
throw new Exception(string.Format("SFTP文件列表获取失败原因{0}", ex.Message));
}
finally
{
Disconnect();
}
}
/// <summary>
/// 获取SFTP文件列表
/// </summary>