从ftp指定目录下载文件的C#代码

 1         /// <summary>
 2         /// Provides the filePath and fileName
 3         /// </summary>
 4         /// <param name="filePath">the path of the file.</param>
 5         /// <param name="fileName">The name of the file.</param>
 6         /// <param name="errorinfo">the error info.</param>        
 7         /// <returns>If this method succeeds, it returns true. Otherwise, it returns an error code and false.</returns>
 8         public bool DownloadFile(string filePath, string fileName, out string errorinfo)
 9         {
10             string onlyFileName = Path.GetFileName(fileName);
11             string newFileName = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + onlyFileName;
12             Log.WriteUserLog(newFileName, 0, 0, 0);
13             errorinfo = string.Empty;
14 
15             if (File.Exists(newFileName))
16             {
17                 //errorinfo = string.Format("本地文件{0}已存在,无法下载", newFileName);
18                 return false;
19             }
20 
21             try
22             {
23                 string url = "ftp://" + ftpServerIP + "/" + fileName;
24                 Connect(url);//连接 
25 
26                 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
27                 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
28                 Stream ftpStream = response.GetResponseStream();
29                 long cl = response.ContentLength;
30                 int bufferSize = 2048;
31                 int readCount;
32                 byte[] buffer = new byte[bufferSize];
33 
34                 readCount = ftpStream.Read(buffer, 0, bufferSize);
35                 FileStream outputStream = new FileStream(newFileName, FileMode.Create);
36 
37                 while (readCount > 0)
38                 {
39                     outputStream.Write(buffer, 0, readCount);
40                     readCount = ftpStream.Read(buffer, 0, bufferSize);
41                 }
42 
43                 ftpStream.Close();
44                 outputStream.Close();
45                 response.Close();
46                 errorinfo = "";
47                 return true;
48             }
49             catch (Exception ex)
50             {
51                 errorinfo = string.Format("因{0},无法下载", ex.Message);
52                 return false;
53             }
54         }
原文地址:https://www.cnblogs.com/caosenianhuan/p/3168917.html