当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《使用带有C#的SSH.NET复制或移动远程文件》经验,为你挑选了1个好方法。



1> LogicFirst..:

可以使用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";
    /// 
    /// Move first file from one source folder to another. 
    /// Note: Modify code and add a for loop to move all files of the folder
    /// 
    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);
            }           
        }
    }

    /// 
    /// Checks if Remote folder contains the given file name
    /// 
    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;
    }

}

推荐阅读
Life一切安好
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有