日期:2014-05-18 浏览次数:21232 次
public static string[] FTPGetFileList(string ftpServerIP, string ftpUserID, string ftpPassword) { //响应结果 StringBuilder result = new StringBuilder(); //FTP请求 FtpWebRequest ftpRequest = null; //FTP响应 WebResponse ftpResponse = null; //FTP响应流 StreamReader ftpResponsStream = null; try { //生成FTP请求 ftpRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/")); //设置文件传输类型 ftpRequest.UseBinary = true; //FTP登录 ftpRequest.Credentials = new NetworkCredential(ftpUserID, ftpPassword); //设置FTP方法 ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails; //生成FTP响应 ftpResponse = ftpRequest.GetResponse(); //FTP响应流 ftpResponsStream = new StreamReader(ftpResponse.GetResponseStream(), System.Text.Encoding.Default); Console.WriteLine(ftpResponsStream.CurrentEncoding); string line = ftpResponsStream.ReadLine(); while (line != null) { if (line.IndexOf("<DIR>") != -1) { Console.WriteLine(line.Substring(39));//此处获得目录名,测试用 result.Append(GetSubFilesList(ftpServerIP,ftpUserID,ftpPassword,line.Substring(39))); } else { result.Append(line); result.Append("\n"); } line = ftpResponsStream.ReadLine(); } //去掉结果列表中最后一个换行 result.Remove(result.ToString().LastIndexOf('\n'), 1); //返回结果 return result.ToString().Split('\n'); } catch (Exception ex) { Console.WriteLine(ex.Message); return (null); } finally { if (ftpResponsStream != null) { ftpResponsStream.Close(); } if (ftpResponse != null) { ftpResponse.Close(); } } } private static string GetSubFilesList(string ftpServerIP,string ftpUserID, string ftpPassword, string StrDir) { //响应结果 StringBuilder result = new StringBuilder(); string struri = "ftp://" + ftpServerIP + "/" + StrDir + "/"; //FTP请求 FtpWebRequest ftpRequest = null; //FTP响应 WebResponse ftpResponse = null; //FTP响应流 StreamReader ftpResponsStream = null; try { ftpRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(struri)); //生成FTP响应 ftpResponse = ftpRequest.GetResponse(); //FTP响应流 ftpResponsStream = new StreamReader(ftpResponse.GetResponseStream(), System.Text.Encoding.Default); Console.WriteLine(ftpResponsStream.CurrentEncoding); string line = ftpResponsStream.ReadLine(); while (line != null) { if (line.IndexOf("<DIR>") != -1) { Console.WriteL