FTPHelper

1   public class FTPHelper
  2     {
  3         #region 字段
  4         /// <summary>
  5         /// ftp地址,带ftp协议
  6         /// </summary>
  7         private string strFtpURI;
  8         /// <summary>
  9         /// ftp用户名
 10         /// </summary>
 11         private string strFtpUserID;
 12         /// <summary>
 13         /// ftp的ip地址
 14         /// </summary>
 15         private string strFtpServerIP;
 16         /// <summary>
 17         /// ftp用户登录密码
 18         /// </summary>
 19         private string strFtpPassword;
 20         /// <summary>
 21         /// ftp目录路径
 22         /// </summary>
 23         private string strFtpRemotePath;
 24         #endregion
 25 
 26         /// <summary>  
 27         /// 连接FTP服务器
 28         /// </summary>  
 29         /// <param name="strFtpServerIP">FTP连接地址</param>  
 30         /// <param name="strFtpRemotePath">指定FTP连接成功后的当前目录, 如果不指定即默认为根目录</param>  
 31         /// <param name="strFtpUserID">用户名</param>  
 32         /// <param name="strFtpPassword">密码</param>  
 33         public FTPHelper(string strFtpServerIP, string strFtpRemotePath, string strFtpUserID, string strFtpPassword)
 34         {
 35             this.strFtpServerIP = strFtpServerIP;
 36             this.strFtpRemotePath = strFtpRemotePath;
 37             this.strFtpUserID = strFtpUserID;
 38             this.strFtpPassword = strFtpPassword;
 39             this.strFtpURI = "ftp://" + strFtpServerIP + strFtpRemotePath;
 40         }
 41 
 42         /// <summary>
 43         /// 上载
 44         /// </summary>
 45         /// <param name="strFilename">本地文件路径</param>
 46         /// <param name="strSavePath">ftp服务器文件保存路径</param>
 47         public void Upload(string strFilename, string strSavePath)
 48         {
 49             FileInfo fileInf = new FileInfo(strFilename);
 50             FtpWebRequest reqFTP;
 51             reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(strFtpURI + strSavePath + fileInf.Name));
 52             reqFTP.Credentials = new NetworkCredential(strFtpUserID, strFtpPassword);
 53             reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
 54             reqFTP.KeepAlive = false;
 55             reqFTP.UseBinary = true;
 56             reqFTP.Proxy = null;
 57             reqFTP.ContentLength = fileInf.Length;
 58             int buffLength = 2048;
 59             byte[] buff = new byte[buffLength];
 60             int contentLen;
 61             FileStream fs = fileInf.OpenRead();
 62             try
 63             {
 64                 Stream strm = reqFTP.GetRequestStream();
 65                 contentLen = fs.Read(buff, 0, buffLength);
 66                 while (contentLen != 0)
 67                 {
 68                     strm.Write(buff, 0, contentLen);
 69                     contentLen = fs.Read(buff, 0, buffLength);
 70                 }
 71                 strm.Close();
 72                 fs.Close();
 73             }
 74             catch (Exception ex)
 75             {
 76                 throw new Exception(ex.Message);
 77             }
 78         }
 79         /// <summary>
 80         /// 上载
 81         /// </summary>
 82         /// <param name="strFilename">本地文件路径</param>
 83         /// <param name="strSavePath">ftp服务器文件保存路径</param>
 84         /// <param name="strStrOldName">ftp服务器文件保存的名字</param>
 85         public void Upload(string strFilename, string strSavePath, string strStrOldName)
 86         {
 87             FileInfo fileInf = new FileInfo(strFilename);
 88             FtpWebRequest reqFTP;
 89             reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(strFtpURI + strSavePath + strStrOldName));
 90             reqFTP.Credentials = new NetworkCredential(strFtpUserID, strFtpPassword);
 91             reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
 92             reqFTP.KeepAlive = false;
 93             reqFTP.UseBinary = true;
 94             reqFTP.Proxy = null;
 95             reqFTP.ContentLength = fileInf.Length;
 96             int buffLength = 2048;
 97             byte[] buff = new byte[buffLength];
 98             int contentLen;
 99             FileStream fs = fileInf.OpenRead();
100             try
101             {
102                 Stream strm = reqFTP.GetRequestStream();
103                 contentLen = fs.Read(buff, 0, buffLength);
104                 while (contentLen != 0)
105                 {
106                     strm.Write(buff, 0, contentLen);
107                     contentLen = fs.Read(buff, 0, buffLength);
108                 }
109                 strm.Close();
110                 fs.Close();
111             }
112             catch (Exception ex)
113             {
114                 throw new Exception(ex.Message);
115             }
116         }
117         /// <summary>
118         /// 下载
119         /// </summary>
120         /// <param name="strFilePath">本地保存路径</param>
121         /// <param name="strFileName">文件名</param> 
122         /// <param name="strFileName">本地临时名称</param>
123         public void Download(string strFilePath, string strFileName, string strLocalName)
124         {
125             try
126             {
127                 FileStream outputStream = new FileStream(strFilePath + strLocalName, FileMode.Create);
128                 FtpWebRequest reqFTP;
129                 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(strFtpURI + strFileName));
130                 reqFTP.Credentials = new NetworkCredential(strFtpUserID, strFtpPassword);
131                 reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
132                 reqFTP.UseBinary = true;
133                 reqFTP.UsePassive = true;
134                 reqFTP.Proxy = null;
135                 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
136                 Stream ftpStream = response.GetResponseStream();
137                 long cl = response.ContentLength;
138                 int bufferSize = 2048;
139                 int readCount;
140                 byte[] buffer = new byte[bufferSize];
141                 readCount = ftpStream.Read(buffer, 0, bufferSize);
142                 while (readCount > 0)
143                 {
144                     outputStream.Write(buffer, 0, readCount);
145                     readCount = ftpStream.Read(buffer, 0, bufferSize);
146                 }
147                 ftpStream.Close();
148                 outputStream.Close();
149                 response.Close();
150             }
151             catch (Exception ex)
152             {
153                 //记录日志
154                 Common.LogHelper.WriteLog("文件下载异常:" + ex.Message);
155             }
156         }
157         /// <summary>
158         /// 下载
159         /// </summary>
160         /// <param name="strFilePath">本地保存路径</param>
161         /// <param name="strFileName">文件名</param>
162         public void Download(string strFilePath, string strFileName)
163         {
164             try
165             {
166                 FileStream outputStream = new FileStream(strFilePath + strFileName, FileMode.Create);
167                 FtpWebRequest reqFTP;
168                 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(strFtpURI + strFileName));
169                 reqFTP.Credentials = new NetworkCredential(strFtpUserID, strFtpPassword);
170                 reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
171                 reqFTP.UseBinary = true;
172                 reqFTP.UsePassive = true;
173                 reqFTP.Proxy = null;
174                 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
175                 Stream ftpStream = response.GetResponseStream();
176                 long cl = response.ContentLength;
177                 int bufferSize = 2048;
178                 int readCount;
179                 byte[] buffer = new byte[bufferSize];
180                 readCount = ftpStream.Read(buffer, 0, bufferSize);
181                 while (readCount > 0)
182                 {
183                     outputStream.Write(buffer, 0, readCount);
184                     readCount = ftpStream.Read(buffer, 0, bufferSize);
185                 }
186                 ftpStream.Close();
187                 outputStream.Close();
188                 response.Close();
189             }
190             catch (Exception ex)
191             {
192                 //记录日志
193                 Common.LogHelper.WriteLog("文件下载异常:" + ex.Message);
194             }
195         }
196         /// <summary>
197         /// 删除文件
198         /// </summary>
199         /// <param name="strFileName">文件名</param>
200         public void Delete(string strFileName)
201         {
202             try
203             {
204                 FtpWebRequest reqFTP;
205                 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(strFtpURI + strFileName));
206                 reqFTP.Credentials = new NetworkCredential(strFtpUserID, strFtpPassword);
207                 reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
208                 reqFTP.KeepAlive = false;
209                 string result = String.Empty;
210                 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
211                 long size = response.ContentLength;
212                 Stream datastream = response.GetResponseStream();
213                 StreamReader sr = new StreamReader(datastream);
214                 result = sr.ReadToEnd();
215                 sr.Close();
216                 datastream.Close();
217                 response.Close();
218             }
219             catch (Exception ex)
220             {
221                 throw new Exception(ex.Message);
222             }
223         }
224 
225         /// <summary>
226         /// 获取当前目录下明细(包含文件和文件夹)  
227         /// </summary>
228         /// <returns></returns>
229         public string[] GetFilesDetailList()
230         {
231             try
232             {
233                 StringBuilder result = new StringBuilder();
234                 FtpWebRequest ftp;
235                 ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(strFtpURI));
236                 ftp.Credentials = new NetworkCredential(strFtpUserID, strFtpPassword);
237                 ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
238                 WebResponse response = ftp.GetResponse();
239                 StreamReader reader = new StreamReader(response.GetResponseStream());
240                 string line = reader.ReadLine();
241                 line = reader.ReadLine();
242                 line = reader.ReadLine();
243                 while (line != null)
244                 {
245                     result.Append(line);
246                     result.Append("\n");
247                     line = reader.ReadLine();
248                 }
249                 result.Remove(result.ToString().LastIndexOf("\n"), 1);
250                 reader.Close();
251                 response.Close();
252                 return result.ToString().Split('\n');
253             }
254             catch (Exception ex)
255             {
256                 throw new Exception(ex.Message);
257             }
258         }
259 
260         /// <summary>
261         ///  获取FTP文件列表(包括文件夹)
262         /// </summary>
263         /// <param name="strUrl"></param>
264         /// <returns></returns>
265         private string[] GetAllList(string strUrl)
266         {
267             List<string> list = new List<string>();
268             FtpWebRequest req = (FtpWebRequest)WebRequest.Create(new Uri(strUrl));
269             req.Credentials = new NetworkCredential(strFtpPassword, strFtpPassword);
270             req.Method = WebRequestMethods.Ftp.ListDirectory;
271             req.UseBinary = true;
272             req.UsePassive = true;
273             try
274             {
275                 using (FtpWebResponse res = (FtpWebResponse)req.GetResponse())
276                 {
277                     using (StreamReader sr = new StreamReader(res.GetResponseStream()))
278                     {
279                         string s;
280                         while ((s = sr.ReadLine()) != null)
281                         {
282                             list.Add(s);
283                         }
284                     }
285                 }
286             }
287             catch (Exception ex)
288             {
289                 throw (ex);
290             }
291             return list.ToArray();
292         }
293 
294         /// <summary>  
295         /// 获取当前目录下文件列表(不包括文件夹)  
296         /// </summary>  
297         public string[] GetFileList(string strUrl)
298         {
299             StringBuilder result = new StringBuilder();
300             FtpWebRequest reqFTP;
301             try
302             {
303                 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(strUrl));
304                 reqFTP.UseBinary = true;
305                 reqFTP.Credentials = new NetworkCredential(strFtpPassword, strFtpPassword);
306                 reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
307                 WebResponse response = reqFTP.GetResponse();
308                 StreamReader reader = new StreamReader(response.GetResponseStream());
309                 string line = reader.ReadLine();
310                 while (line != null)
311                 {
312 
313                     if (line.IndexOf("<DIR>") == -1)
314                     {
315                         result.Append(Regex.Match(line, @"[\S]+ [\S]+", RegexOptions.IgnoreCase).Value.Split(' ')[1]);
316                         result.Append("\n");
317                     }
318                     line = reader.ReadLine();
319                 }
320                 result.Remove(result.ToString().LastIndexOf('\n'), 1);
321                 reader.Close();
322                 response.Close();
323             }
324             catch (Exception ex)
325             {
326                 throw (ex);
327             }
328             return result.ToString().Split('\n');
329         }
330 
331         /// <summary>  
332         /// 判断当前目录下指定的文件是否存在  
333         /// </summary>  
334         /// <param name="strRemoteFileName">远程文件名</param>  
335         public bool FileExist(string strRemoteFileName)
336         {
337             string[] fileList = GetFileList("*.*");
338             foreach (string str in fileList)
339             {
340                 if (str.Trim() == strRemoteFileName.Trim())
341                 {
342                     return true;
343                 }
344             }
345             return false;
346         }
347 
348         /// <summary>
349         /// 创建文件夹  
350         /// </summary>
351         /// <param name="strDirName">目录名</param>
352         public void MakeDir(string strDirName)
353         {
354             FtpWebRequest reqFTP;
355             try
356             {
357                 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(strFtpURI + strDirName));
358                 reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
359                 reqFTP.UseBinary = true;
360                 reqFTP.Credentials = new NetworkCredential(strFtpUserID, strFtpPassword);
361                 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
362                 Stream ftpStream = response.GetResponseStream();
363                 ftpStream.Close();
364                 response.Close();
365             }
366             catch (Exception ex)
367             { Common.LogHelper.WriteLog("ftp服务器创建目录异常:" + ex.Message); }
368         }
369 
370         /// <summary>  
371         /// 获取指定文件大小  
372         /// </summary>  
373         public long GetFileSize(string strFilename)
374         {
375             FtpWebRequest reqFTP;
376             long fileSize = 0;
377             try
378             {
379                 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(strFtpURI + strFilename));
380                 reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
381                 reqFTP.UseBinary = true;
382                 reqFTP.Credentials = new NetworkCredential(strFtpUserID, strFtpPassword);
383                 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
384                 Stream ftpStream = response.GetResponseStream();
385                 fileSize = response.ContentLength;
386                 ftpStream.Close();
387                 response.Close();
388             }
389             catch (Exception ex)
390             { throw ex; }
391             return fileSize;
392         }
393 
394         /// <summary>  
395         /// 更改文件名  
396         /// </summary> 
397         public void ReName(string strCurrentFilename, string strNewFilename)
398         {
399             FtpWebRequest reqFTP;
400             try
401             {
402                 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(strFtpURI + strCurrentFilename));
403                 reqFTP.Method = WebRequestMethods.Ftp.Rename;
404                 reqFTP.RenameTo = strNewFilename;
405                 reqFTP.UseBinary = true;
406                 reqFTP.Credentials = new NetworkCredential(strFtpUserID, strFtpPassword);
407                 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
408                 Stream ftpStream = response.GetResponseStream();
409                 ftpStream.Close();
410                 response.Close();
411             }
412             catch (Exception ex)
413             { throw ex; }
414         }
415 
416         /// <summary>  
417         /// 移动文件  
418         /// </summary>  
419         public void MovieFile(string strCurrentFilename, string strNewDirectory)
420         {
421             ReName(strCurrentFilename, strNewDirectory);
422         }
423 
424         /// <summary>  
425         /// 切换当前目录  
426         /// </summary>  
427         /// <param name="bIsRoot">true:绝对路径 false:相对路径</param>   
428         public void GotoDirectory(string strDirectoryName, bool bIsRoot)
429         {
430             if (bIsRoot)
431             {
432                 strFtpRemotePath = strDirectoryName;
433             }
434             else
435             {
436                 strFtpRemotePath += strDirectoryName + "/";
437             }
438             strFtpURI = "ftp://" + strFtpServerIP + "/" + strFtpRemotePath + "/";
439         }
440     }

FTPHelper