c# 从ftp上下载文件
工具推荐:
IIS7服务器管理工具是一款windows全系、Linux系统下链接并操控VPS、VNC、FTP等远程服务器、云服务器。
界面简单明了,操作易上手,功能强大,支持批量导入服务器,并批量打开,多窗口化管理,除此之外,加载本地硬盘、硬盘映射、加载服务器的声音,远程声卡读取等,完全实现各类场景使用,对于FTP链接界面,朋友FTP定时上传,定时下载(也可以说定时上传下载 定时备份),对于经常使用FTP的小伙伴来说,非常适用。
工具支持自动更新,压缩包只有7.62M,方便简洁,一步到位。
下载地址:http://yczm.iis7.com/?tscc
private void Button1_Click(object sender, EventArgs e) { string uri = "ftp://172.17.13.127/"; string username = "username"; string password = "pwd"; var list = FtplistFile(uri,username,password); string path = @"D:\Example"; foreach (var item in list) { Ftpdownloadfile(Path.Combine(uri, item), Path.Combine(path,item),username,password); } MessageBox.Show("success"); } private List<string> FtplistFile(string url,string username,string password) //get file name form ftp folder { FtpWebRequest listRequest = (FtpWebRequest)WebRequest.Create(url); listRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails; listRequest.Credentials = new NetworkCredential(username, password); List<string> lines = new List<string>(); using (FtpWebResponse listResponse = (FtpWebResponse)listRequest.GetResponse()) using (Stream listStream = listResponse.GetResponseStream()) using (StreamReader listReader = new StreamReader(listStream)) { while (!listReader.EndOfStream) { lines.Add(listReader.ReadLine()); } } List<string> name = new List<string>(); foreach (var line in lines) { string[] tokens = line.Split(new[] { ' ' }, 9, StringSplitOptions.RemoveEmptyEntries); string n = tokens[3]; name.Add(n); } return name; } private void Ftpdownloadfile(string to_uri,string path,string username,string password) { FtpWebRequest request = (FtpWebRequest)WebRequest.Create(to_uri); request.Method = WebRequestMethods.Ftp.DownloadFile; request.Credentials = new NetworkCredential(username, password); using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) { using (Stream responseStream = response.GetResponseStream()) { using (FileStream fs = new FileStream(path, FileMode.Create)) { byte[] buffer = new byte[102400]; int read = 0; do { read = responseStream.Read(buffer, 0, buffer.Length); fs.Write(buffer, 0, read); fs.Flush(); } while (!(read == 0)); fs.Flush(); fs.Close(); } } } }