• C# FTP操作类(获取文件和文件夹列表)


    一.如何获取某一目录下的文件和文件夹列表。

    由于FtpWebRequest类只提供了WebRequestMethods.Ftp.ListDirectory方式和WebRequestMethods.Ftp.ListDirectoryDetails方式。这个方法获取到的是包含文件列表和文件夹列表的信息。并不是单单只包含某一类。为此我们需要分析获取信息的特点。分析发现,对于文件夹会有“<DIR>”这一项,而文件没有。所以我们可以根据这个来区分。一下分别是获取文件列表和文件夹列表的代码:

    1.获取文件夹列表:

     1 /// <summary>
     2 /// 从ftp服务器上获得文件夹列表
     3 /// </summary>
     4 /// <param name="RequedstPath">服务器下的相对路径</param>
     5 /// <returns></returns>
     6 public static List<string> GetDirctory(string RequedstPath)
     7 {
     8     List<string> strs = new List<string>();
     9     try
    10     {
    11         string uri = path + RequedstPath;   //目标路径 path为服务器地址
    12         FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
    13         // ftp用户名和密码
    14         reqFTP.Credentials = new NetworkCredential(username, password);
    15         reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
    16         WebResponse response = reqFTP.GetResponse();
    17         StreamReader reader = new StreamReader(response.GetResponseStream());//中文文件名
    18 
    19         string line = reader.ReadLine();
    20         while (line != null)
    21         {
    22             if (line.Contains("<DIR>"))
    23             {
    24                 string msg = line.Substring(line.LastIndexOf("<DIR>")+5).Trim();
    25                 strs.Add(msg);
    26             }
    27             line = reader.ReadLine();
    28         }
    29         reader.Close();
    30         response.Close();
    31         return strs;
    32     }
    33     catch (Exception ex)
    34     {
    35         Console.WriteLine("获取目录出错:" + ex.Message);
    36     }
    37     return strs;
    38 }
    View Code

    2.获取文件列表

     1 /// <summary>
     2 /// 从ftp服务器上获得文件列表
     3 /// </summary>
     4 /// <param name="RequedstPath">服务器下的相对路径</param>
     5 /// <returns></returns>
     6 public static List<string> GetFile(string RequedstPath)
     7 {
     8     List<string> strs = new List<string>();
     9     try
    10     {
    11         string uri = path + RequedstPath;   //目标路径 path为服务器地址
    12         FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
    13         // ftp用户名和密码
    14         reqFTP.Credentials = new NetworkCredential(username, password);
    15         reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
    16         WebResponse response = reqFTP.GetResponse();
    17         StreamReader reader = new StreamReader(response.GetResponseStream());//中文文件名
    18 
    19         string line = reader.ReadLine();
    20         while (line != null)
    21         {
    22             if (!line.Contains("<DIR>"))
    23             {
    24                 string msg = line.Substring(39).Trim();
    25                 strs.Add(msg);
    26             }
    27             line = reader.ReadLine();
    28         }
    29         reader.Close();
    30         response.Close();
    31         return strs;
    32     }
    33     catch (Exception ex)
    34     {
    35         Console.WriteLine("获取文件出错:" + ex.Message);
    36     }
    37     return strs;
    38 }
    View Code

    二.其他代码

      1 using System;
      2 using System.Collections.Generic;
      3 using System.Linq;
      4 using System.Text;
      5 using System.Net;
      6 using System.IO;
      7 using System.Threading;
      8 
      9 namespace FtpSyn
     10 {
     11     static public class FtpHelper
     12     {
     13         //基本设置
     14         static private string path = @"ftp://" + Helper.GetAppConfig("obj") + "/";    //目标路径
     15         static private string ftpip =Helper.GetAppConfig("obj");    //ftp IP地址
     16         static private string username = Helper.GetAppConfig("username");   //ftp用户名
     17         static private string password = Helper.GetAppConfig("password");   //ftp密码
     18 
     19         //获取ftp上面的文件和文件夹
     20         public static string[] GetFileList(string dir)
     21         {
     22             string[] downloadFiles;
     23             StringBuilder result = new StringBuilder();
     24             FtpWebRequest request;
     25             try
     26             {
     27                 request = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));
     28                 request.UseBinary = true;
     29                 request.Credentials = new NetworkCredential(username, password);//设置用户名和密码
     30                 request.Method = WebRequestMethods.Ftp.ListDirectory;
     31                 request.UseBinary = true;
     32 
     33                 WebResponse response = request.GetResponse();
     34                 StreamReader reader = new StreamReader(response.GetResponseStream());
     35 
     36                 string line = reader.ReadLine();
     37                 while (line != null)
     38                 {
     39                     result.Append(line);
     40                     result.Append("
    ");
     41                     Console.WriteLine(line);
     42                     line = reader.ReadLine();
     43                 }
     44                 // to remove the trailing '
    '
     45                 result.Remove(result.ToString().LastIndexOf('
    '), 1);
     46                 reader.Close();
     47                 response.Close();
     48                 return result.ToString().Split('
    ');
     49             }
     50             catch (Exception ex)
     51             {
     52                 Console.WriteLine("获取ftp上面的文件和文件夹:" + ex.Message);
     53                 downloadFiles = null;
     54                 return downloadFiles;
     55             }
     56         }
     57 
     58         /// <summary>
     59         /// 获取文件大小
     60         /// </summary>
     61         /// <param name="file">ip服务器下的相对路径</param>
     62         /// <returns>文件大小</returns>
     63         public static int GetFileSize(string file)
     64         {
     65             StringBuilder result = new StringBuilder();
     66             FtpWebRequest request;
     67             try
     68             {
     69                 request = (FtpWebRequest)FtpWebRequest.Create(new Uri(path + file));
     70                 request.UseBinary = true;
     71                 request.Credentials = new NetworkCredential(username, password);//设置用户名和密码
     72                 request.Method = WebRequestMethods.Ftp.GetFileSize;
     73 
     74                 int dataLength = (int)request.GetResponse().ContentLength;
     75 
     76                 return dataLength;
     77             }
     78             catch (Exception ex)
     79             {
     80                 Console.WriteLine("获取文件大小出错:" + ex.Message);
     81                 return -1;
     82             }
     83         }
     84 
     85         /// <summary>
     86         /// 文件上传
     87         /// </summary>
     88         /// <param name="filePath">原路径(绝对路径)包括文件名</param>
     89         /// <param name="objPath">目标文件夹:服务器下的相对路径 不填为根目录</param>
     90         public static void FileUpLoad(string filePath,string objPath="")
     91         {
     92             try
     93             {
     94                 string url = path;
     95                 if(objPath!="")
     96                     url += objPath + "/";
     97                 try
     98                 {
     99 
    100                     FtpWebRequest reqFTP = null;
    101                     //待上传的文件 (全路径)
    102                     try
    103                     {
    104                         FileInfo fileInfo = new FileInfo(filePath);
    105                         using (FileStream fs = fileInfo.OpenRead())
    106                         {
    107                             long length = fs.Length;
    108                             reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(url + fileInfo.Name));
    109 
    110                             //设置连接到FTP的帐号密码
    111                             reqFTP.Credentials = new NetworkCredential(username, password);
    112                             //设置请求完成后是否保持连接
    113                             reqFTP.KeepAlive = false;
    114                             //指定执行命令
    115                             reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
    116                             //指定数据传输类型
    117                             reqFTP.UseBinary = true;
    118 
    119                             using (Stream stream = reqFTP.GetRequestStream())
    120                             {
    121                                 //设置缓冲大小
    122                                 int BufferLength = 5120;
    123                                 byte[] b = new byte[BufferLength];
    124                                 int i;
    125                                 while ((i = fs.Read(b, 0, BufferLength)) > 0)
    126                                 {
    127                                     stream.Write(b, 0, i);
    128                                 }
    129                                 Console.WriteLine("上传文件成功");
    130                             }
    131                         }
    132                     }
    133                     catch (Exception ex)
    134                     {
    135                         Console.WriteLine("上传文件失败错误为" + ex.Message);
    136                     }
    137                     finally
    138                     {
    139 
    140                     }
    141                 }
    142                 catch (Exception ex)
    143                 {
    144                     Console.WriteLine("上传文件失败错误为" + ex.Message);
    145                 }
    146                 finally
    147                 {
    148 
    149                 }
    150             }
    151             catch (Exception ex)
    152             {
    153                 Console.WriteLine("上传文件失败错误为" + ex.Message);
    154             }
    155         }
    156         
    157         /// <summary>
    158         /// 删除文件
    159         /// </summary>
    160         /// <param name="fileName">服务器下的相对路径 包括文件名</param>
    161         public static void DeleteFileName(string fileName)
    162         {
    163             try
    164             {
    165                 FileInfo fileInf = new FileInfo(ftpip +""+ fileName);
    166                 string uri = path + fileName;
    167                 FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
    168                 // 指定数据传输类型
    169                 reqFTP.UseBinary = true;
    170                 // ftp用户名和密码
    171                 reqFTP.Credentials = new NetworkCredential(username, password);
    172                 // 默认为true,连接不会被关闭
    173                 // 在一个命令之后被执行
    174                 reqFTP.KeepAlive = false;
    175                 // 指定执行什么命令
    176                 reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
    177                 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
    178                 response.Close();
    179             }
    180             catch (Exception ex)
    181             {
    182                 Console.WriteLine("删除文件出错:" + ex.Message);
    183             }
    184         }
    185         
    186         /// <summary>
    187         /// 新建目录 上一级必须先存在
    188         /// </summary>
    189         /// <param name="dirName">服务器下的相对路径</param>
    190         public static void MakeDir(string dirName)
    191         {
    192             try
    193             {
    194                 string uri = path + dirName;
    195                 FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
    196                 // 指定数据传输类型
    197                 reqFTP.UseBinary = true;
    198                 // ftp用户名和密码
    199                 reqFTP.Credentials = new NetworkCredential(username, password);
    200                 reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
    201                 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
    202                 response.Close();
    203             }
    204             catch (Exception ex)
    205             {
    206                 Console.WriteLine("创建目录出错:" + ex.Message);
    207             }
    208         }
    209         
    210         /// <summary>
    211         /// 删除目录 上一级必须先存在
    212         /// </summary>
    213         /// <param name="dirName">服务器下的相对路径</param>
    214         public static void DelDir(string dirName)
    215         {
    216             try
    217             {
    218                 string uri = path + dirName;
    219                 FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
    220                 // ftp用户名和密码
    221                 reqFTP.Credentials = new NetworkCredential(username, password);
    222                 reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory;
    223                 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
    224                 response.Close();
    225             }
    226             catch (Exception ex)
    227             {
    228                 Console.WriteLine("删除目录出错:" + ex.Message);
    229             }
    230         }
    231 
    232         /// <summary>
    233         /// 从ftp服务器上获得文件夹列表
    234         /// </summary>
    235         /// <param name="RequedstPath">服务器下的相对路径</param>
    236         /// <returns></returns>
    237         public static List<string> GetDirctory(string RequedstPath)
    238         {
    239             List<string> strs = new List<string>();
    240             try
    241             {
    242                 string uri = path + RequedstPath;   //目标路径 path为服务器地址
    243                 FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
    244                 // ftp用户名和密码
    245                 reqFTP.Credentials = new NetworkCredential(username, password);
    246                 reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
    247                 WebResponse response = reqFTP.GetResponse();
    248                 StreamReader reader = new StreamReader(response.GetResponseStream());//中文文件名
    249 
    250                 string line = reader.ReadLine();
    251                 while (line != null)
    252                 {
    253                     if (line.Contains("<DIR>"))
    254                     {
    255                         string msg = line.Substring(line.LastIndexOf("<DIR>")+5).Trim();
    256                         strs.Add(msg);
    257                     }
    258                     line = reader.ReadLine();
    259                 }
    260                 reader.Close();
    261                 response.Close();
    262                 return strs;
    263             }
    264             catch (Exception ex)
    265             {
    266                 Console.WriteLine("获取目录出错:" + ex.Message);
    267             }
    268             return strs;
    269         }
    270 
    271         /// <summary>
    272         /// 从ftp服务器上获得文件列表
    273         /// </summary>
    274         /// <param name="RequedstPath">服务器下的相对路径</param>
    275         /// <returns></returns>
    276         public static List<string> GetFile(string RequedstPath)
    277         {
    278             List<string> strs = new List<string>();
    279             try
    280             {
    281                 string uri = path + RequedstPath;   //目标路径 path为服务器地址
    282                 FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
    283                 // ftp用户名和密码
    284                 reqFTP.Credentials = new NetworkCredential(username, password);
    285                 reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
    286                 WebResponse response = reqFTP.GetResponse();
    287                 StreamReader reader = new StreamReader(response.GetResponseStream());//中文文件名
    288 
    289                 string line = reader.ReadLine();
    290                 while (line != null)
    291                 {
    292                     if (!line.Contains("<DIR>"))
    293                     {
    294                         string msg = line.Substring(39).Trim();
    295                         strs.Add(msg);
    296                     }
    297                     line = reader.ReadLine();
    298                 }
    299                 reader.Close();
    300                 response.Close();
    301                 return strs;
    302             }
    303             catch (Exception ex)
    304             {
    305                 Console.WriteLine("获取文件出错:" + ex.Message);
    306             }
    307             return strs;
    308         }
    309     
    310     }
    311 }
    View Code

    转自:http://www.cnblogs.com/rond/archive/2012/07/30/2611295.html

  • 相关阅读:
    【题解】P2569 [SCOI2010]股票交易
    【题解】P3354 [IOI2005]Riv 河流
    入职阿里蚂蚁三个月有感
    搞懂G1垃圾收集器
    MySql分库分表与分区的区别和思考
    Kafka源码分析及图解原理之Broker端
    Kafka源码分析及图解原理之Producer端
    Oracle GoldenGate mysql To Kafka上车记录
    从动态代理到Spring AOP(中)
    从动态代理到Spring AOP(上)
  • 原文地址:https://www.cnblogs.com/programsky/p/5787638.html
Copyright © 2020-2023  润新知