Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/268.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用SSH.NET和C复制或移动远程文件#_C#_.net_Sftp_Ssh.net - Fatal编程技术网

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

C# 使用SSH.NET和C复制或移动远程文件#,c#,.net,sftp,ssh.net,C#,.net,Sftp,Ssh.net,我知道我可以使用SSH.NET库的SftpClient类从SFTP服务器上传和下载文件,但我不确定如何使用该类在SFTP服务器上复制或移动远程文件。我也没有在网上找到相关资料。如何使用SSH.NET库和C#将远程文件从目录a复制或移动到目录B 更新: 我还尝试使用下面的代码来试验SshClient类,但它什么也不做,既没有任何错误,也没有任何异常 ConnectionInfo ConnNfo = new ConnectionInfo("FTPHost", 22, "FTPUser", new A

我知道我可以使用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();
}
在VisualStudio控制台上,我得到以下输出

*日志详细信息:1:发送消息到服务器“ChannelRequestMessage”:“SSH_MSG_CHANNEL_REQUEST:#152199”

SshNet.Logging详细信息:1:ReceiveMessage from server: 'ChannelFailureMessage':'SSH_MSG_CHANNEL_FAILURE:#0'*


可以使用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;
    }

}
使用系统;
使用System.Linq;
使用System.Collections.Generic;
使用Renci.SshNet;
使用Renci.SshNet.Sftp;
使用System.IO;
使用系统配置;
使用系统IO压缩;
公共类RemoteFileOperations
{
私有字符串ftppathrcfolder=“/Path/Source/”;//路径应以结尾/
私有字符串ftpPathDestFolder=“/Path/Archive/”;//路径应以结尾/
私有字符串ftpServerIP=“目标IP”;
private int ftpPortNumber=80;//更改为适当的端口号
私有字符串ftpUserID=“FTP用户名”//
私有字符串ftpPassword=“FTP密码”;
/// 
///将第一个文件从一个源文件夹移动到另一个源文件夹。
///注意:修改代码并添加for循环以移动文件夹的所有文件
/// 
public void MoveFolderToArchive()
{
使用(SftpClient sftp=新的SftpClient(ftpServerIP、ftpPortNumber、ftpUserID、ftpPassword))
{
SftpFile eachRemoteFile=sftp.ListDirectory(ftppath srcfolder).First();//获取目录中的第一个文件
if(eachRemoteFile.IsRegularFile)//仅移动文件
{
bool eachFileExistsInArchive=CheckIfRemoteFileExists(sftp、ftpPathDestFolder、eachRemoteFile.Name);
//如果目标文件夹中存在文件名alredy,则MoveTo将导致错误。请检查文件名是否存在以防止该错误
字符串eachFileNameInArchive=eachRemoteFile.Name;
如果(每个文件存在存档)
{
eachfilenameinrachive=eachfilenameinrachive+“\u”+DateTime.Now.ToString(“mmddyyy\u HHmmss”);//如果文件已经存在,请更改文件名
}
移动到(ftpPathDestFolder+chive中的每个文件名);
}           
}
}
/// 
///检查远程文件夹是否包含给定的文件名
/// 
public bool CheckIfRemoteFileExists(SftpClient SftpClient,string remoteFolderName,string remotefileName)
{
bool isFileExists=sftpClient
.ListDirectory(remoteFolderName)
.任何(
f=>f.IsRegularFile&&
f、 Name.ToLower()==remotefileName.ToLower()
);
返回isFileExists;
}
}

除了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);
    }
}

对于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();

您能在cmd中远程登录ftp服务器吗?我可以使用WinSCP实用程序成功连接和复制粘贴文件。除此之外,我还可以使用SSH.NET库的“SftpClient”类成功连接和下载文件。如果使用RunCommand而不是CreateCommand如何?此链接可能很有用:Works。确保在项目中包含SSH.NET。我使用了Nuget软件包管理器。这是目前为止最简单、最好的解决方案,也是唯一对我有效的解决方案。您没有刷新fsIn
fsIn
有什么原因吗?我认为fsOut.flush()基本上强制了fsIn.flush(),但不是100%确定