• C#操作FTP, FTPHelper和SFTPHelper


    1. FTPHelper

      1 using System;
      2 using System.Collections.Generic;
      3 using System.IO;
      4 using System.Net;
      5 using System.Text;
      6 
      7 public class FTPHelper
      8     {
      9         /// <summary>
     10         /// 上传文件
     11         /// </summary>
     12         /// <param name="fileinfo">需要上传的文件</param>
     13         /// <param name="targetDir">目标路径</param>
     14         /// <param name="hostname">ftp地址</param>
     15         /// <param name="username">ftp用户名</param>
     16         /// <param name="password">ftp密码</param>
     17         public static void UploadFile(FileInfo fileinfo, string targetDir, string hostname, string username, string password)
     18         {
     19             //1. check target
     20             string target;
     21             if (targetDir.Trim() == "")
     22             {
     23                 return;
     24             }
     25             string filename = fileinfo.Name;
     26             if (!string.IsNullOrEmpty(filename))
     27                 target = filename;
     28             else
     29                 target = Guid.NewGuid().ToString();  //使用临时文件名
     30 
     31             string URI = "FTP://" + hostname + "/" + targetDir + "/" + target;
     32             ///WebClient webcl = new WebClient();
     33             System.Net.FtpWebRequest ftp = GetRequest(URI, username, password);
     34 
     35             //设置FTP命令 设置所要执行的FTP命令,
     36             //ftp.Method = System.Net.WebRequestMethods.Ftp.ListDirectoryDetails;//假设此处为显示指定路径下的文件列表
     37             ftp.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
     38             //指定文件传输的数据类型
     39             ftp.UseBinary = true;
     40             ftp.UsePassive = true;
     41 
     42             //告诉ftp文件大小
     43             ftp.ContentLength = fileinfo.Length;
     44             //缓冲大小设置为2KB
     45             const int BufferSize = 2048;
     46             byte[] content = new byte[BufferSize - 1 + 1];
     47             int dataRead;
     48 
     49             //打开一个文件流 (System.IO.FileStream) 去读上传的文件
     50             using (FileStream fs = fileinfo.OpenRead())
     51             {
     52                 try
     53                 {
     54                     //把上传的文件写入流
     55                     using (Stream rs = ftp.GetRequestStream())
     56                     {
     57                         do
     58                         {
     59                             //每次读文件流的2KB
     60                             dataRead = fs.Read(content, 0, BufferSize);
     61                             rs.Write(content, 0, dataRead);
     62                         } while (!(dataRead < BufferSize));
     63                         rs.Close();
     64                     }
     65 
     66                 }
     67                 catch (Exception ex) { }
     68                 finally
     69                 {
     70                     fs.Close();
     71                 }
     72 
     73             }
     74 
     75             ftp = null;
     76         }
     77 
     78         /// <summary>
     79         /// 下载文件
     80         /// </summary>
     81         /// <param name="localDir">下载至本地路径</param>
     82         /// <param name="FtpDir">ftp目标文件路径</param>
     83         /// <param name="FtpFile">从ftp要下载的文件名</param>
     84         /// <param name="hostname">ftp地址即IP</param>
     85         /// <param name="username">ftp用户名</param>
     86         /// <param name="password">ftp密码</param>
     87         public static void DownloadFile(string localDir, string FtpDir, string FtpFile, string hostname, string username, string password)
     88         {
     89             string URI = "FTP://" + hostname + "/" + FtpDir + "/" + FtpFile;
     90             string tmpname = Guid.NewGuid().ToString();
     91             string localfile = localDir + @"" + tmpname;
     92 
     93             System.Net.FtpWebRequest ftp = GetRequest(URI, username, password);
     94             ftp.Method = System.Net.WebRequestMethods.Ftp.DownloadFile;
     95             ftp.UseBinary = true;
     96             ftp.UsePassive = false;
     97 
     98             using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
     99             {
    100                 using (Stream responseStream = response.GetResponseStream())
    101                 {
    102                     //loop to read & write to file
    103                     using (FileStream fs = new FileStream(localfile, FileMode.CreateNew))
    104                     {
    105                         try
    106                         {
    107                             byte[] buffer = new byte[2048];
    108                             int read = 0;
    109                             do
    110                             {
    111                                 read = responseStream.Read(buffer, 0, buffer.Length);
    112                                 fs.Write(buffer, 0, read);
    113                             } while (!(read == 0));
    114                             responseStream.Close();
    115                             fs.Flush();
    116                             fs.Close();
    117                         }
    118                         catch (Exception)
    119                         {
    120                             //catch error and delete file only partially downloaded
    121                             fs.Close();
    122                             //delete target file as it's incomplete
    123                             File.Delete(localfile);
    124                             throw;
    125                         }
    126                     }
    127 
    128                     responseStream.Close();
    129                 }
    130 
    131                 response.Close();
    132             }
    133 
    134 
    135 
    136             try
    137             {
    138                 File.Delete(localDir + @"" + FtpFile);
    139                 File.Move(localfile, localDir + @"" + FtpFile);
    140 
    141 
    142                 ftp = null;
    143                 ftp = GetRequest(URI, username, password);
    144                 ftp.Method = System.Net.WebRequestMethods.Ftp.DeleteFile;
    145                 ftp.GetResponse();
    146 
    147             }
    148             catch (Exception ex)
    149             {
    150                 File.Delete(localfile);
    151                 throw ex;
    152             }
    153 
    154             // 记录日志 "从" + URI.ToString() + "下载到" + localDir + @"" + FtpFile + "成功." );
    155             ftp = null;
    156         }
    157 
    158 
    159         /// <summary>
    160         /// 下载文件
    161         /// </summary>
    162         /// <param name="localDir">下载至本地路径</param>
    163         /// <param name="FtpDir">ftp目标文件路径</param>
    164         /// <param name="FtpFile">从ftp要下载的文件名</param>
    165         /// <param name="hostname">ftp地址即IP</param>
    166         /// <param name="username">ftp用户名</param>
    167         /// <param name="password">ftp密码</param>
    168         public static byte[] DownloadFileBytes(string localDir, string FtpDir, string FtpFile, string hostname, string username, string password)
    169         {
    170             byte[] bts;
    171             string URI = "FTP://" + hostname + "/" + FtpDir + "/" + FtpFile;
    172             string tmpname = Guid.NewGuid().ToString();
    173             string localfile = localDir + @"" + tmpname;
    174 
    175             System.Net.FtpWebRequest ftp = GetRequest(URI, username, password);
    176             ftp.Method = System.Net.WebRequestMethods.Ftp.DownloadFile;
    177             ftp.UseBinary = true;
    178             ftp.UsePassive = true;
    179 
    180             using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
    181             {
    182                 using (Stream responseStream = response.GetResponseStream())
    183                 {
    184                     //loop to read & write to file
    185                     using (MemoryStream fs = new MemoryStream())
    186                     {
    187                         try
    188                         {
    189                             byte[] buffer = new byte[2048];
    190                             int read = 0;
    191                             do
    192                             {
    193                                 read = responseStream.Read(buffer, 0, buffer.Length);
    194                                 fs.Write(buffer, 0, read);
    195                             } while (!(read == 0));
    196                             responseStream.Close();
    197 
    198                             //---
    199                             byte[] mbt = new byte[fs.Length];
    200                             fs.Read(mbt, 0, mbt.Length);
    201 
    202                             bts = mbt;
    203                             //---
    204                             fs.Flush();
    205                             fs.Close();
    206                         }
    207                         catch (Exception)
    208                         {
    209                             //catch error and delete file only partially downloaded
    210                             fs.Close();
    211                             //delete target file as it's incomplete
    212                             File.Delete(localfile);
    213                             throw;
    214                         }
    215                     }
    216 
    217                     responseStream.Close();
    218                 }
    219 
    220                 response.Close();
    221             }
    222 
    223             ftp = null;
    224             return bts;
    225         }
    226 
    227         /// <summary>
    228         /// 搜索远程文件
    229         /// </summary>
    230         /// <param name="targetDir"></param>
    231         /// <param name="hostname"></param>
    232         /// <param name="username"></param>
    233         /// <param name="password"></param>
    234         /// <param name="SearchPattern"></param>
    235         /// <returns></returns>
    236         public static List<string> ListDirectory(string targetDir, string hostname, string username, string password, string SearchPattern)
    237         {
    238             List<string> result = new List<string>();
    239             try
    240             {
    241                 string URI = "FTP://" + hostname + "/" + targetDir + "/" + SearchPattern;
    242 
    243                 System.Net.FtpWebRequest ftp = GetRequest(URI, username, password);
    244                 ftp.Method = System.Net.WebRequestMethods.Ftp.ListDirectory;
    245                 ftp.UsePassive = true;
    246                 ftp.UseBinary = true;
    247 
    248 
    249                 string str = GetStringResponse(ftp);
    250                 str = str.Replace("
    ", "
    ").TrimEnd('
    ');
    251                 str = str.Replace("
    ", "
    ");
    252                 if (str != string.Empty)
    253                     result.AddRange(str.Split('
    '));
    254 
    255                 return result;
    256             }
    257             catch { }
    258             return null;
    259         }
    260 
    261         private static string GetStringResponse(FtpWebRequest ftp)
    262         {
    263             //Get the result, streaming to a string
    264             string result = "";
    265             using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
    266             {
    267                 long size = response.ContentLength;
    268                 using (Stream datastream = response.GetResponseStream())
    269                 {
    270                     using (StreamReader sr = new StreamReader(datastream, System.Text.Encoding.Default))
    271                     {
    272                         result = sr.ReadToEnd();
    273                         sr.Close();
    274                     }
    275 
    276                     datastream.Close();
    277                 }
    278 
    279                 response.Close();
    280             }
    281 
    282             return result;
    283         }
    284 
    285         /// 在ftp服务器上创建目录
    286         /// </summary>
    287         /// <param name="dirName">创建的目录名称</param>
    288         /// <param name="ftpHostIP">ftp地址</param>
    289         /// <param name="username">用户名</param>
    290         /// <param name="password">密码</param>
    291         public void MakeDir(string dirName, string ftpHostIP, string username, string password)
    292         {
    293             try
    294             {
    295                 string uri = "ftp://" + ftpHostIP + "/" + dirName;
    296                 System.Net.FtpWebRequest ftp = GetRequest(uri, username, password);
    297                 ftp.Method = WebRequestMethods.Ftp.MakeDirectory;
    298 
    299                 FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
    300                 response.Close();
    301             }
    302             catch (Exception ex)
    303             {
    304                 throw new Exception(ex.Message);
    305             }
    306         }
    307 
    308         /// <summary>
    309         /// 删除文件
    310         /// </summary>
    311         /// <param name="dirName">创建的目录名称</param>
    312         /// <param name="ftpHostIP">ftp地址</param>
    313         /// <param name="username">用户名</param>
    314         /// <param name="password">密码</param>
    315         public static void delFile(string dirName, string filename, string ftpHostIP, string username, string password)
    316         {
    317             try
    318             {
    319                 string uri = "ftp://" + ftpHostIP + "/";
    320                 if (!string.IsNullOrEmpty(dirName)) {
    321                     uri += dirName + "/";
    322                 }
    323                 uri += filename;
    324                 System.Net.FtpWebRequest ftp = GetRequest(uri, username, password);
    325                 ftp.Method = WebRequestMethods.Ftp.DeleteFile;
    326                 FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
    327                 response.Close();
    328             }
    329             catch (Exception ex)
    330             {
    331                 throw new Exception(ex.Message);
    332             }
    333         }
    334 
    335         /// <summary>
    336         /// 删除目录
    337         /// </summary>
    338         /// <param name="dirName">创建的目录名称</param>
    339         /// <param name="ftpHostIP">ftp地址</param>
    340         /// <param name="username">用户名</param>
    341         /// <param name="password">密码</param>
    342         public void delDir(string dirName, string ftpHostIP, string username, string password)
    343         {
    344             try
    345             {
    346                 string uri = "ftp://" + ftpHostIP + "/" + dirName;
    347                 System.Net.FtpWebRequest ftp = GetRequest(uri, username, password);
    348                 ftp.Method = WebRequestMethods.Ftp.RemoveDirectory;
    349                 FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
    350                 response.Close();
    351             }
    352             catch (Exception ex)
    353             {
    354                 throw new Exception(ex.Message);
    355             }
    356         }
    357 
    358         /// <summary>
    359         /// 文件重命名
    360         /// </summary>
    361         /// <param name="currentFilename">当前目录名称</param>
    362         /// <param name="newFilename">重命名目录名称</param>
    363         /// <param name="ftpServerIP">ftp地址</param>
    364         /// <param name="username">用户名</param>
    365         /// <param name="password">密码</param>
    366         public void Rename(string currentFilename, string newFilename, string ftpServerIP, string username, string password)
    367         {
    368             try
    369             {
    370 
    371                 FileInfo fileInf = new FileInfo(currentFilename);
    372                 string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
    373                 System.Net.FtpWebRequest ftp = GetRequest(uri, username, password);
    374                 ftp.Method = WebRequestMethods.Ftp.Rename;
    375 
    376                 ftp.RenameTo = newFilename;
    377                 FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
    378 
    379                 response.Close();
    380             }
    381             catch (Exception ex)
    382             {
    383                 throw new Exception(ex.Message);
    384             }
    385         }
    386 
    387         private static FtpWebRequest GetRequest(string URI, string username, string password)
    388         {
    389             //根据服务器信息FtpWebRequest创建类的对象
    390             FtpWebRequest result = (FtpWebRequest)FtpWebRequest.Create(URI);
    391             //提供身份验证信息
    392             result.Credentials = new System.Net.NetworkCredential(username, password);
    393             //设置请求完成之后是否保持到FTP服务器的控制连接,默认值为true
    394             result.KeepAlive = false;
    395             return result;
    396         }
    397 
    398         /*
    399         /// <summary>
    400         /// 向Ftp服务器上传文件并创建和本地相同的目录结构
    401         /// 遍历目录和子目录的文件
    402         /// </summary>
    403         /// <param name="file"></param>
    404         private void GetFileSystemInfos(FileSystemInfo file)
    405         {
    406             string getDirecName = file.Name;
    407             if (!ftpIsExistsFile(getDirecName, "192.168.0.172", "Anonymous", "") && file.Name.Equals(FileName))
    408             {
    409                 MakeDir(getDirecName, "192.168.0.172", "Anonymous", "");
    410             }
    411             if (!file.Exists) return;
    412             DirectoryInfo dire = file as DirectoryInfo;
    413             if (dire == null) return;
    414             FileSystemInfo[] files = dire.GetFileSystemInfos();
    415 
    416             for (int i = 0; i < files.Length; i++)
    417             {
    418                 FileInfo fi = files[i] as FileInfo;
    419                 if (fi != null)
    420                 {
    421                     DirectoryInfo DirecObj = fi.Directory;
    422                     string DireObjName = DirecObj.Name;
    423                     if (FileName.Equals(DireObjName))
    424                     {
    425                         UploadFile(fi, DireObjName, "192.168.0.172", "Anonymous", "");
    426                     }
    427                     else
    428                     {
    429                         Match m = Regex.Match(files[i].FullName, FileName + "+.*" + DireObjName);
    430                         //UploadFile(fi, FileName+"/"+DireObjName, "192.168.0.172", "Anonymous", "");
    431                         UploadFile(fi, m.ToString(), "192.168.0.172", "Anonymous", "");
    432                     }
    433                 }
    434                 else
    435                 {
    436                     string[] ArrayStr = files[i].FullName.Split('\');
    437                     string finame = files[i].Name;
    438                     Match m = Regex.Match(files[i].FullName, FileName + "+.*" + finame);
    439                     //MakeDir(ArrayStr[ArrayStr.Length - 2].ToString() + "/" + finame, "192.168.0.172", "Anonymous", "");
    440                     MakeDir(m.ToString(), "192.168.0.172", "Anonymous", "");
    441                     GetFileSystemInfos(files[i]);
    442                 }
    443             }
    444         }
    445          * */
    446 
    447         /// <summary>
    448         /// 判断ftp服务器上该目录是否存在
    449         /// </summary>
    450         /// <param name="dirName"></param>
    451         /// <param name="ftpHostIP"></param>
    452         /// <param name="username"></param>
    453         /// <param name="password"></param>
    454         /// <returns></returns>
    455         private bool ftpIsExistsFile(string dirName, string ftpHostIP, string username, string password)
    456         {
    457             bool flag = true;
    458             try
    459             {
    460                 string uri = "ftp://" + ftpHostIP + "/" + dirName;
    461                 System.Net.FtpWebRequest ftp = GetRequest(uri, username, password);
    462                 ftp.Method = WebRequestMethods.Ftp.ListDirectory;
    463 
    464                 FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
    465                 response.Close();
    466             }
    467             catch (Exception)
    468             {
    469                 flag = false;
    470             }
    471             return flag;
    472         }
    473     }
    View Code


    2. SFTPHelper

    SFTPHelper采用第三方的Tamir.SharpSSH.dll

    下载地址: http://www.tamirgal.com/blog/page/SharpSSH.aspx

      1 using System;
      2 using Tamir.SharpSsh.jsch;
      3 using System.Collections;
      4 
      5 
      6 public class SFTPHelper
      7 {
      8     private Session m_session;
      9     private Channel m_channel;
     10     private ChannelSftp m_sftp;
     11 
     12     //host:sftp地址   user:用户名   pwd:密码        
     13     public SFTPHelper(string host, string user, string pwd)
     14     {
     15         string[] arr = host.Split(':');
     16         string ip = arr[0];
     17         int port = 22;
     18         if (arr.Length > 1) port = Int32.Parse(arr[1]);
     19 
     20         JSch jsch = new JSch();
     21         m_session = jsch.getSession(user, ip, port);
     22         MyUserInfo ui = new MyUserInfo();
     23         ui.setPassword(pwd);
     24         m_session.setUserInfo(ui);
     25 
     26     }
     27 
     28     //SFTP连接状态        
     29     public bool Connected { get { return m_session.isConnected(); } }
     30 
     31     //连接SFTP        
     32     public bool Connect()
     33     {
     34         try
     35         {
     36             if (!Connected)
     37             {
     38                 m_session.connect();
     39                 m_channel = m_session.openChannel("sftp");
     40                 m_channel.connect();
     41                 m_sftp = (ChannelSftp)m_channel;
     42             }
     43             return true;
     44         }
     45         catch
     46         {
     47             return false;
     48         }
     49     }
     50 
     51     //断开SFTP        
     52     public void Disconnect()
     53     {
     54         if (Connected)
     55         {
     56             m_channel.disconnect();
     57             m_session.disconnect();
     58         }
     59     }
     60 
     61     //SFTP存放文件        
     62     public bool Put(string localPath, string remotePath)
     63     {
     64         try
     65         {
     66             Tamir.SharpSsh.java.String src = new Tamir.SharpSsh.java.String(localPath);
     67             Tamir.SharpSsh.java.String dst = new Tamir.SharpSsh.java.String(remotePath);
     68             m_sftp.put(src, dst);
     69             return true;
     70         }
     71         catch
     72         {
     73             return false;
     74         }
     75     }
     76 
     77     //SFTP获取文件        
     78     public bool Get(string remotePath, string localPath)
     79     {
     80         try
     81         {
     82             Tamir.SharpSsh.java.String src = new Tamir.SharpSsh.java.String(remotePath);
     83             Tamir.SharpSsh.java.String dst = new Tamir.SharpSsh.java.String(localPath);
     84             m_sftp.get(src, dst);
     85             return true;
     86         }
     87         catch
     88         {
     89             return false;
     90         }
     91     }
     92     //删除SFTP文件
     93     public bool Delete(string remoteFile)
     94     {
     95         try
     96         {
     97             m_sftp.rm(remoteFile);
     98             return true;
     99         }
    100         catch
    101         {
    102             return false;
    103         }
    104     }
    105 
    106     //获取SFTP文件列表        
    107     public ArrayList GetFileList(string remotePath, string fileType)
    108     {
    109         try
    110         {
    111             Tamir.SharpSsh.java.util.Vector vvv = m_sftp.ls(remotePath);
    112             ArrayList objList = new ArrayList();
    113             foreach (Tamir.SharpSsh.jsch.ChannelSftp.LsEntry qqq in vvv)
    114             {
    115                 string sss = qqq.getFilename();
    116                 if (sss.Length > (fileType.Length + 1) && fileType == sss.Substring(sss.Length - fileType.Length))
    117                 { objList.Add(sss); }
    118                 else { continue; }
    119             }
    120 
    121             return objList;
    122         }
    123         catch
    124         {
    125             return null;
    126         }
    127     }
    128 
    129 
    130     //登录验证信息        
    131     public class MyUserInfo : UserInfo
    132     {
    133         String passwd;
    134         public String getPassword() { return passwd; }
    135         public void setPassword(String passwd) { this.passwd = passwd; }
    136 
    137         public String getPassphrase() { return null; }
    138         public bool promptPassphrase(String message) { return true; }
    139 
    140         public bool promptPassword(String message) { return true; }
    141         public bool promptYesNo(String message) { return true; }
    142         public void showMessage(String message) { }
    143     }
    144 
    145 
    146 }
    View Code
  • 相关阅读:
    spring MVC的启动过程详解
    BeanFactory和applicationContext之间的区别
    spring的事务管理
    通用Mybatis的Crud搭建
    spring的IOC原理
    spring的AOP原理
    TortoiseSVN使用简介
    SVN简明教程
    POJO
    velocity 框架
  • 原文地址:https://www.cnblogs.com/kkwoo/p/3488642.html
Copyright © 2020-2023  润新知