Fra*_*cis 6 c# ssh sftp ssh.net
我在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));
}
}
}
Run Code Online (Sandbox Code Playgroud)
这适用于单个文件.现在我想上传整个文件夹/目录.
现在有人如何实现这一目标?
没有神奇的方法.您必须枚举文件并逐个上传它们:
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 (Stream 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);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)