C#怎么获取ftp上的所有文件路径和子目录路径,怎么上传和下载整个文件夹(里面有文件夹和文件)
2 回答
侃侃尔雅
TA贡献1801条经验 获得超16个赞
FTP获取文件路径和子目录路径
知道如何获取文件和目录,剩下的就是一个递归而已。这个很简单,不说明了。递归这东西好玩,但是效率很低。
Ron Ngai | 园豆:296 (菜鸟二级) | 2012-07-25 18:28
/// <summary> /// 从ftp服务器上获得文件列表 /// </summary> /// <param name="RequedstPath"></param> /// <returns></returns> public static List<string> GetDirctory(string RequedstPath) { List<string> strs = new List<string>(); try { string uri = path + RequedstPath; //目标路径 path为服务器地址 FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); // ftp用户名和密码 reqFTP.Credentials = new NetworkCredential(username, password); reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails; WebResponse response = reqFTP.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream());//中文文件名 string line = reader.ReadLine(); while (line != null) { if (line.Contains("<DIR>")) { string msg = line.Substring(line.LastIndexOf("<DIR>")+5).Trim(); strs.Add(msg); } line = reader.ReadLine(); } reader.Close(); response.Close(); return strs; } catch (Exception ex) { Console.WriteLine("获取目录出错:" + ex.Message); } return strs; } /// <summary> /// 从ftp服务器上获得文件 /// </summary> /// <param name="RequedstPath">相对服务器路径</param> /// <returns></returns> public static List<string> GetFile(string RequedstPath) { List<string> strs = new List<string>(); try { string uri = path + RequedstPath; //目标路径 path为服务器地址 FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); // ftp用户名和密码 reqFTP.Credentials = new NetworkCredential(username, password); reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails; WebResponse response = reqFTP.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream());//中文文件名 string line = reader.ReadLine(); while (line != null) { if (!line.Contains("<DIR>")) { string msg = line.Substring(39).Trim(); strs.Add(msg); Console.WriteLine(msg); } line = reader.ReadLine(); } reader.Close(); response.Close(); return strs; } catch (Exception ex) { Console.WriteLine("获取文件出错:" + ex.Message); } return strs; }
- 2 回答
- 0 关注
- 2334 浏览
添加回答
举报
0/150
提交
取消