【问题标题】:Copying or moving a remote file using SSH.NET with C#使用 SSH.NET 和 C# 复制或移动远程文件
【发布时间】:2020-03-25 20:55:33
【问题描述】:

我知道我可以使用 SSH.NET 库的SftpClient 类从 SFTP 服务器上传和下载文件,但我不确定如何使用此类在 SFTP 服务器上复制或移动远程文件.我也没有在互联网上找到相关材料。如何使用 SSH.NET 库和 C# 将远程文件从目录 A 复制或移动到目录 B。

更新: 我还尝试使用下面的代码尝试 SshClient 类,但它什么也没做,既没有任何错误也没有任何异常。

ConnectionInfo ConnNfo = new ConnectionInfo("FTPHost", 22, "FTPUser",
new AuthenticationMethod[]{

   // Pasword based Authentication
   new PasswordAuthenticationMethod("FTPUser","FTPPass")
   }                
   );

using (var ssh = new SshClient(ConnNfo))
{
    ssh.Connect();                
    if (ssh.IsConnected)
    {                    
         string comm = "pwd";
         using (var cmd = ssh.CreateCommand(comm))
         {
            var returned = cmd.Execute();
            var output = cmd.Result;
            var err = cmd.Error;
            var stat = cmd.ExitStatus;
         }
     }
   ssh.Disconnect();
}

在 Visual Studio 控制台上,我得到以下输出。

*SshNet.Logging Verbose: 1 : SendMessage to server 'ChannelRequestMessage': 'SSH_MSG_CHANNEL_REQUEST : #152199'。

SshNet.Logging 详细:1:来自服务器的 ReceiveMessage: 'ChannelFailureMessage': 'SSH_MSG_CHANNEL_FAILURE : #0'.*

【问题讨论】:

  • 你能用 cmd telnet ftp 服务器吗?
  • 我可以使用 WinSCP 实用程序成功连接和复制粘贴文件。除此之外,我可以使用 SSH.NET 库的“SftpClient”类成功连接和下载文件。
  • 如果你使用 RunCommand 代替 CreateCommand 怎么样?

标签: c# .net sftp ssh.net


【解决方案1】:

除了 SSH.NET 的 SftpClient 之外,还有更简单的 ScpClient 在我遇到 SftpClient 问题时起作用。 ScpClient 仅具有上传/下载功能,但这满足了我的用例。

上传中:

using (ScpClient client = new ScpClient(host, username, password))
{
    client.Connect();

    using (Stream localFile = File.OpenRead(localFilePath))
    {
         client.Upload(localFile, remoteFilePath);
    }
}

正在下载:

using (ScpClient client = new ScpClient(host, username, password))
{
    client.Connect();

    using (Stream localFile = File.Create(localFilePath))
    {
         client.Download(remoteFilePath, localFile);
    }
}

【讨论】:

  • 有效。确保在您的项目中包含 SSH.NET。我使用了 Nuget 包管理器。
  • 是否有上传进度的信息?
【解决方案2】:

可以使用 SSH.NET 库来移动远程文件。可在此处获取:https://github.com/sshnet/SSH.NET

这是将第一个文件从一个源文件夹移动到另一个的示例代码。根据FTP设置在类中设置私有变量。

using System;
using System.Linq;
using System.Collections.Generic;
using Renci.SshNet;
using Renci.SshNet.Sftp;
using System.IO;
using System.Configuration;
using System.IO.Compression;

public class RemoteFileOperations
{
    private string ftpPathSrcFolder = "/Path/Source/";//path should end with /
    private string ftpPathDestFolder = "/Path/Archive/";//path should end with /
    private string ftpServerIP = "Target IP";
    private int ftpPortNumber = 80;//change to appropriate port number
    private string ftpUserID = "FTP USer Name";//
    private string ftpPassword = "FTP Password";
    /// <summary>
    /// Move first file from one source folder to another. 
    /// Note: Modify code and add a for loop to move all files of the folder
    /// </summary>
    public void MoveFolderToArchive()
    {
        using (SftpClient sftp = new SftpClient(ftpServerIP, ftpPortNumber, ftpUserID, ftpPassword))
        {
            SftpFile eachRemoteFile = sftp.ListDirectory(ftpPathSrcFolder).First();//Get first file in the Directory            
            if(eachRemoteFile.IsRegularFile)//Move only file
            {
                bool eachFileExistsInArchive = CheckIfRemoteFileExists(sftp, ftpPathDestFolder, eachRemoteFile.Name);

                //MoveTo will result in error if filename alredy exists in the target folder. Prevent that error by cheking if File name exists
                string eachFileNameInArchive = eachRemoteFile.Name;

                if (eachFileExistsInArchive)
                {
                    eachFileNameInArchive = eachFileNameInArchive + "_" + DateTime.Now.ToString("MMddyyyy_HHmmss");//Change file name if the file already exists
                }
                eachRemoteFile.MoveTo(ftpPathDestFolder + eachFileNameInArchive);
            }           
        }
    }

    /// <summary>
    /// Checks if Remote folder contains the given file name
    /// </summary>
    public bool CheckIfRemoteFileExists(SftpClient sftpClient, string remoteFolderName, string remotefileName)
    {
        bool isFileExists = sftpClient
                            .ListDirectory(remoteFolderName)
                            .Any(
                                    f => f.IsRegularFile &&
                                    f.Name.ToLower() == remotefileName.ToLower()
                                );
        return isFileExists;
    }

}

【讨论】:

  • 感谢有关在移动文件之前检查文件是否已存在的建议。我收到了一般的Failure 错误,但实际上它是由这个问题引起的。
【解决方案3】:

使用 Renci 的 NuGet 包 SSH.NET,我使用以下内容:

using Renci.SshNet;
using Renci.SshNet.SftpClient;    

...

        SftpClient _sftp = new SftpClient(_host, _username, _password);

移动文件:

        var inFile = _sftp.Get(inPath);
        inFile.MoveTo(outPath);

复制文件:

       var fsIn = _sftp.OpenRead(inPath);
       var fsOut = _sftp.OpenWrite(outPath);

        int data;
        while ((data = fsIn.ReadByte()) != -1)
            fsOut.WriteByte((byte)data);

        fsOut.Flush();
        fsIn.Close();
        fsOut.Close();

【讨论】:

  • 这是迄今为止最简单和最好的解决方案,也是唯一对我有用的解决方案。
  • 你没有刷新fsIn的原因是什么?
  • 我认为 fsOut.Flush() 本质上是强制 fsIn.Flush() 但不是 100% 确定
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-10
相关资源
最近更新 更多