首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用SSH.NET和C#复制或移动远程文件

使用SSH.NET和C#复制或移动远程文件
EN

Stack Overflow用户
提问于 2015-12-09 14:35:26
回答 3查看 63.9K关注 0票数 12

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

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

代码语言:javascript
运行
复制
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控制台上,我得到以下输出。

*SshNet.Logging详细:1: SendMessage到服务器'ChannelRequestMessage':'SSH_MSG_CHANNEL_REQUEST:#152199‘。 SshNet.Logging详细:1:来自服务器的ReceiveMessage:'ChannelFailureMessage':'SSH_MSG_CHANNEL_FAILURE:#0'.*

EN

回答 3

Stack Overflow用户

发布于 2018-06-13 19:25:15

除了SSH.NET的SftpClient之外,还有一个更简单的ScpClient,当我遇到SftpClient问题时,它可以工作。ScpClient只具有上传/下载功能,但这满足了我的用例。

上传:

代码语言:javascript
运行
复制
using (ScpClient client = new ScpClient(host, username, password))
{
    client.Connect();

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

下载中:

代码语言:javascript
运行
复制
using (ScpClient client = new ScpClient(host, username, password))
{
    client.Connect();

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

Stack Overflow用户

发布于 2018-10-04 18:02:34

对于NuGet包SSH.NET by Renci,我使用以下方法:

代码语言:javascript
运行
复制
using Renci.SshNet;
using Renci.SshNet.SftpClient;    

...

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

要移动文件:

代码语言:javascript
运行
复制
        var inFile = _sftp.Get(inPath);
        inFile.MoveTo(outPath);

要复制文件:

代码语言:javascript
运行
复制
       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();
票数 16
EN

Stack Overflow用户

发布于 2016-08-29 17:51:59

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

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

代码语言:javascript
运行
复制
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;
    }

}
票数 15
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34181447

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档