gpt4 book ai didi

c# - SSH.NET 上传整个文件夹

转载 作者:太空狗 更新时间:2023-10-29 21:21:28 25 4
gpt4 key购买 nike

我在 C# 2015 中使用 SSH.NET。

通过这种方法,我可以将文件上传到我的 SFTP 服务器。

public void upload()
{
const int port = 22;
const string host = "*****";
const string username = "*****";
const string password = "*****";
const string workingdirectory = "*****";
string uploadfolder = @"C:\test\file.txt";

Console.WriteLine("Creating client and connecting");
using (var client = new SftpClient(host, port, username, password))
{
client.Connect();
Console.WriteLine("Connected to {0}", host);

client.ChangeDirectory(workingdirectory);
Console.WriteLine("Changed directory to {0}", workingdirectory);

using (var fileStream = new FileStream(uploadfolder, FileMode.Open))
{
Console.WriteLine("Uploading {0} ({1:N0} bytes)",
uploadfolder, fileStream.Length);
client.BufferSize = 4 * 1024; // bypass Payload error large files
client.UploadFile(fileStream, Path.GetFileName(uploadfolder));
}
}
}

这对单个文件非常有效。现在我想上传整个文件夹/目录。

现在有人知道如何实现吗?

最佳答案

没有神奇的方法。您必须枚举文件并一个一个上传:

void UploadDirectory(SftpClient client, string localPath, string remotePath)
{
Console.WriteLine("Uploading directory {0} to {1}", localPath, remotePath);

IEnumerable<FileSystemInfo> infos =
new DirectoryInfo(localPath).EnumerateFileSystemInfos();
foreach (FileSystemInfo info in infos)
{
if (info.Attributes.HasFlag(FileAttributes.Directory))
{
string subPath = remotePath + "/" + info.Name;
if (!client.Exists(subPath))
{
client.CreateDirectory(subPath);
}
UploadDirectory(client, info.FullName, remotePath + "/" + info.Name);
}
else
{
using (var fileStream = new FileStream(info.FullName, FileMode.Open))
{
Console.WriteLine(
"Uploading {0} ({1:N0} bytes)",
info.FullName, ((FileInfo)info).Length);

client.UploadFile(fileStream, remotePath + "/" + info.Name);
}
}
}
}

如果你想要一个更简单的代码,你将不得不使用另一个库。例如我的 WinSCP .NET assembly可以使用一次调用 Session.PutFilesToDirectory 上传整个目录:

var results = session.PutFilesToDirectory(localPath, remotePath);
results.Check();

关于c# - SSH.NET 上传整个文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39397746/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com