public List<string> GetFileList(string srcpath)
{
List<string> list = new List<string>();
FtpWebRequest reqFtp;
WebResponse response = null;
StreamReader reader = null;
string uri = string.Format("ftp://{0}/{1}",ftpServerIP,srcpath);
try
{
reqFtp = (FtpWebRequest)FtpWebRequest.Create(uri);
reqFtp.UseBinary = true;
reqFtp.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFtp.Method = WebRequestMethods.Ftp.ListDirectory;
response = reqFtp.GetResponse();
reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
string line = reader.ReadLine();
while (line != null)
{
if (!string.IsNullOrEmpty(line.Trim()))
{
list.Add(line.Trim());
}
line = reader.ReadLine();
}
reader.Close();
response.Close();
}
catch
{
if (reader != null)
{
reader.Close();
}
if (response != null)
{
response.Close();
}
}
return list;
}
使用.NET类库中的类,先获取文件列表,然后再下载
上面的方法有个问题,会将目录下面的目录也列进来,然后下载的时候会在下载目录里面生成一个与目录名同名的并且占0字节的文件
比如
\a.txt ----- 文件 xxx字节
\b ------文件夹 0字节
\c -------文件 xxx字节
\d --------文件 0字节
那么得到的文件列表就是 a.txt b c d,下载后下载目录中有文件
\a.txt ----- 文件 xxx字节
\b ------文件 0字节
\c -------文件 xxx字节
\d --------文件 0字节
现在的问题是,我只需要列出文件,不需要文件夹,该用什么方式来呢
(1) 使用扩展名是不可行的,虽然在windows一般文件都是带有扩展名的,但是也会存在无扩展名的文件,如上面列出的c,d都是文件,一样没有扩展名
(2)使用文件大小来判断也是不可行的,文件夹占用空间为0,如果将0字节大小的不列入文件列表,但是如 d,本身是占用0字节的
问题解决了,获益良多
用WebRequestMethods.Ftp.ListDirectoryDetails;
获取的string判断第一个字符是不是 'd',如果是 d 就是 目录
就是不知道为什么微软不再封装一下,毕竟对获取的 detail string使用 substring来得到需要的信息,感觉还是 hardcode,如果对detail string不熟悉的话,也想不到这个方法