C#获取FTP目录下文件夹、文件的方法,进而判断FTP下指定文件夹是否存在
直接说方法:1 public string[] GetFileList()
2 {
3 string[] downloadFiles;
4 StringBuilder result = new StringBuilder();
5 FtpWebRequest reqFTP;
6 try
7 {
8 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(@ftp://192.168.13.1 + "/"));
9 reqFTP.UseBinary = true;
10 reqFTP.Credentials = new NetworkCredential("Administrator","123456");
11 reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
12 WebResponse response = reqFTP.GetResponse();
13 StreamReader reader = new StreamReader(response.GetResponseStream(),Encoding.Default);
14
15 string line = reader.ReadLine();
16 while (line != null)
17 {
18 result.Append(line);
19 result.Append("\n");
20 line = reader.ReadLine();
21 }
22 // to remove the trailing '\n'
23 result.Remove(result.ToString().LastIndexOf('\n'), 1);
24
25
26 reader.Close();
27 response.Close();
28 return result.ToString().Split('\n');
29 }
30 catch (Exception ex)
31 {
32 System.Windows.Forms.MessageBox.Show(ex.Message);
33 downloadFiles = null;
34 return downloadFiles;
35 }
36 }
解释一下,这个方法就是获取FTP目录下所有的文件(注意:不包括文件夹,在网上搜索说是获取FTP下的文件和文件夹,但是经过本人在自己的FTP上测试,只能获取到文件的名字,无法获取FTP下文件夹的名字)。
其中,ftp://192.168.13.1为FTP的目录。也可写成ftp://192.168.13.1/a,即获取FTP目录下a这个文件夹下的所有文件名称。
Administrator为连接FTP所需的用户名,123456为用户名密码,根据需要更改。
reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;这句代码就是实现FTP的ListDirectory方法,即获取文件名。
如果是需要获取FTP下所有文件夹的名字,那就麻烦一点儿了,需要把Ftp的方法修改为ListDirectoryDetails。即代码:
reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
修改为
reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
这样是获取FTP目录下所有的文件和文件夹的名字。
综上所示,可以获取FTP指定目录下的文件名,也可获取FTP指定目录下的文件和文件夹名。那么获取FTP指定目录下文件夹的名字是不是就出来了呢,这样就可以实现判断FTP目录下指定文件夹是否存在了,有点儿绕弯,不过也是一种方法。
也就是对字符串的操作了,这个就不多讲了。自己实现,有需要留言~
页:
[1]