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

由于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

相关文章:

  • 2022-12-23
  • 2021-06-19
  • 2021-08-29
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-10-02
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-21
  • 2021-12-16
相关资源
相似解决方案