12FtpWebRequest上传下载
Posted 清幽火焰
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了12FtpWebRequest上传下载相关的知识,希望对你有一定的参考价值。
下载文件
1 /// <summary> 2 /// 下载文件 3 /// </summary> 4 /// <param name="filename"></param> 5 private static void DownLoadFile(string filename) 6 { 7 FtpWebRequest req = (FtpWebRequest)WebRequest.Create("ftp://" + FtpAddress + "/" + filename); 8 req.Method = WebRequestMethods.Ftp.DownloadFile; 9 req.UseBinary = true; 10 req.UsePassive = true; 11 req.Credentials = new NetworkCredential(FtpUid, FtpPwd); 12 try 13 { 14 using (FtpWebResponse res = (FtpWebResponse)req.GetResponse()) 15 { 16 string localfile = Path.Combine(LocalPath, filename); 17 FileStream fs = new FileStream(localfile, FileMode.Create, FileAccess.Write); 18 int buffer = 1024; //1K缓冲 19 byte[] b = new byte[buffer]; 20 int i = 0; 21 Stream stream = res.GetResponseStream(); 22 while ((i = stream.Read(b, 0, buffer)) > 0) 23 { 24 fs.Write(b, 0, i); 25 } 26 } 27 Console.WriteLine(filename + " download!"); 28 Log(filename + "下载成功"); 29 30 } 31 catch (Exception ex) 32 { 33 Console.WriteLine(ex.ToString()); 34 Log(ex.ToString()); 35 } 36 finally 37 { 38 39 } 40 }
获取文件列表
1 /// <summary> 2 /// 获取FTP文件列表 3 /// </summary> 4 /// <returns></returns> 5 private static List<String> GetFileList() 6 { 7 List<string> list = new List<string>(); 8 FtpWebRequest req = (FtpWebRequest)WebRequest.Create(new Uri("ftp://" + FtpAddress + FtpRemotePath)); 9 req.Credentials = new NetworkCredential(FtpUid, FtpPwd); 10 req.Method = WebRequestMethods.Ftp.ListDirectory; 11 req.UseBinary = true; 12 req.UsePassive = true; 13 try 14 { 15 using (FtpWebResponse res = (FtpWebResponse)req.GetResponse()) 16 { 17 using (StreamReader sr = new StreamReader(res.GetResponseStream())) 18 { 19 string s; 20 while ((s = sr.ReadLine()) != null) 21 { 22 23 list.Add(s); 24 } 25 } 26 } 27 } 28 catch (Exception ex) 29 { 30 Console.WriteLine(ex.ToString()); 31 Log("下载文件列表失败:"); 32 Log(ex.ToString()); 33 } 34 return list; 35 36 }
上传文件
1 private static void UploadFile(string localFile) 2 { 3 FileInfo fi = new FileInfo(localFile); 4 FileStream fs = fi.OpenRead(); 5 long length = fs.Length; 6 FtpWebRequest req = (FtpWebRequest)WebRequest.Create("ftp://" + FtpAddress + FtpRemotePath + fi.Name); 7 req.Credentials = new NetworkCredential(FtpUid, FtpPwd); 8 req.Method = WebRequestMethods.Ftp.UploadFile; 9 req.UseBinary = true; 10 req.ContentLength = length; 11 req.Timeout = 10 * 1000; 12 try 13 { 14 Stream stream = req.GetRequestStream(); 15 16 int BufferLength = 2048; //2K 17 byte[] b = new byte[BufferLength]; 18 int i; 19 while ((i = fs.Read(b, 0, BufferLength)) > 0) 20 { 21 stream.Write(b, 0, i); 22 } 23 stream.Close(); 24 stream.Dispose(); 25 26 } 27 catch (Exception ex) 28 { 29 Console.WriteLine(ex.ToString()); 30 } 31 32 }
以上是关于12FtpWebRequest上传下载的主要内容,如果未能解决你的问题,请参考以下文章
为啥 FtpWebRequest 恰好在长传输结束时抛出 WebException?
使用 C# 到 FTP 文件到大型机,包括数据集 - 将 FTP 脚本翻译成 FtpWebRequest 代码
使用 FtpWebRequest 附加到大型机上的文件时出现问题