由于服务商从FTP服务器迁移到SFTP服务器,唉~~~,苦逼的我们就改来该去的吧。现在来稍微说说这个是怎么实现的。
----------------------------------------我是无耻的分割线------------------------------------------------------------
就不赘述FTP和SFTP的区别了,只提一点在一定的程度上后者更安全,需要的同学请移步http://www.cnblogs.com/mfryf/archive/2013/05/29/3107286.html了解更多,谢谢!
好了,既然要到服务器上去操作文件,我们首先要登陆服务器,就像登陆其他服务器一样,我们需要一个地址、用户名、密码,可能还需要一个端口号。
这里我是借助于一个第三方的插件,SharpSSH 1.1.1.13,这是地址http://www.tamirgal.com/blog/page/SharpSSH.aspx(可以自行下载)。
--需要引用的dll
using Tamir.SharpSsh;
using AmazonASNService.BLL;
class sftpHelp { private SshTransferProtocolBase m_sshCp; private sftpHelp() { } public sftpHelp(SshConnectionInfo connectionInfo) { m_sshCp = new Sftp(connectionInfo.Host, connectionInfo.User); if (connectionInfo.Pass != null) { m_sshCp.Password = connectionInfo.Pass; } if (connectionInfo.IdentityFile != null) { m_sshCp.AddIdentityFile(connectionInfo.IdentityFile); } } public bool Connected { get { return m_sshCp.Connected; } } public void Connect() { if (!m_sshCp.Connected) { m_sshCp.Connect(); } } public void Close() { if (m_sshCp.Connected) { m_sshCp.Close(); } } //上传 public bool Upload(string localPath, string remotePath,int port) { try { if (!m_sshCp.Connected) { m_sshCp.Connect(port);//如果没有端口号的话可以忽略 } m_sshCp.Put(localPath, remotePath); return true; } catch { return false; } } //下载 public bool Download(string remotePath, string localPath,int port) { try { if (!m_sshCp.Connected) { m_sshCp.Connect(port); } m_sshCp.Get(remotePath, localPath); return true; } catch { return false; } }
public bool Delete(string remotePath) { try { if (!m_sshCp.Connected) { m_sshCp.Connect(); } ((Sftp)m_sshCp).Delete(remotePath);//刚刚新增的Delete方法 return true; } catch { return false; } } public ArrayList GetFileList(string path,int port) { try { if (!m_sshCp.Connected) { m_sshCp.Connect(port); } return ((Sftp)m_sshCp).GetFileList(path); } catch(Exception ex) { return null; } } }
/// <summary> /// sftp上传文件 /// </summary> private static void UploadSftp() { SshConnectionInfo objInfo = new SshConnectionInfo(); objInfo.User = ftpUserID; objInfo.Host = ftpServerIP; objInfo.Pass = ftpPassword; //基于密码 sftpHelp objSFTPHelper = new sftpHelp(objInfo); string[] strFiles = Directory.GetFiles(poapath); if (strFiles != null) { foreach (string strFile in strFiles) { if ( objSFTPHelper.Upload(strFile, ftpDir,2222))//开始上传 { File.Delete(strFile); } } } }
/// <summary> /// 2.从SFTP获取文件到指定目录 /// </summary> private static void DownSFTPFile() { SshConnectionInfo SsInfo=new SshConnectionInfo(); SsInfo.User = ftpUserID; SsInfo.Host = ftpServerIP; //SsInfo.IdentityFile = "key"; //有2中认证,一种基于PrivateKey,一种基于password SsInfo.Pass = ftpPassword; //基于密码 sftpHelp sftpDown = new sftpHelp(SsInfo); ArrayList FileList = sftpDown.GetFileList(ftpPath,2222); if (FileList != null) { for (int i = 0; i < FileList.Count; i++) { string sfileName = ftpPath + "/" + FileList[i]; if (sftpDown.Download(sfileName, downPath,2222)) { sftpDown.Delete(sfileName,2222); } } } }