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

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

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值