FTP访问类

  1   public class FtpHelper
  2   {
  3     string ftpServerIP;
  4     string ftpRemotePath;
  5     string ftpUserID;
  6     string ftpPassword;
  7     string ftpURI;
  8     /// <summary>
  9     /// 连接FTP
 10     /// </summary>
 11     /// <param name="FtpServerIP">FTP连接地址</param>
 12     /// <param name="FtpRemotePath">指定FTP连接成功后的当前目录, 如果不指定即默认为根目录</param>
 13     /// <param name="FtpUserID">用户名</param>
 14     /// <param name="FtpPassword">密码</param>
 15     public FtpHelper(string FtpServerIP, string FtpRemotePath, string FtpUserID, string FtpPassword)
 16     {
 17       ftpServerIP = FtpServerIP;
 18       ftpRemotePath = FtpRemotePath;
 19       ftpUserID = FtpUserID;
 20       ftpPassword = FtpPassword;
 21       ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";
 22     }
 23     /// <summary>
 24     /// 上传
 25     /// </summary>
 26     /// <param name="filename"></param>
 27     public void Upload(string filename)
 28     {
 29       FileInfo fileInf = new FileInfo(filename);
 30       string uri = ftpURI + fileInf.Name;
 31       FtpWebRequest reqFTP;
 32       reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
 33       reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
 34       reqFTP.KeepAlive = false;
 35       reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
 36       reqFTP.UseBinary = true;
 37       reqFTP.ContentLength = fileInf.Length;
 38       int buffLength = 2048;
 39       byte[] buff = new byte[buffLength];
 40       int contentLen;
 41       FileStream fs = fileInf.OpenRead();
 42       try
 43       {
 44         Stream strm = reqFTP.GetRequestStream();
 45         contentLen = fs.Read(buff, 0, buffLength);
 46         while (contentLen != 0)
 47         {
 48           strm.Write(buff, 0, contentLen);
 49           contentLen = fs.Read(buff, 0, buffLength);
 50         }
 51         strm.Close();
 52         fs.Close();
 53       }
 54       catch (Exception ex)
 55       {
 56         Insert_Standard_ErrorLog.Insert("FtpHelper", "Upload Error --> " + ex.Message);
 57       }
 58     }
 59     /// <summary>
 60     /// 下载
 61     /// </summary>
 62     /// <param name="filePath"></param>
 63     /// <param name="fileName"></param>
 64     public void Download(string filePath, string fileName)
 65     {
 66       FtpWebRequest reqFTP;
 67       try
 68       {
 69         FileStream outputStream = new FileStream(filePath + "\" + fileName, FileMode.Create);
 70         reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileName));
 71         reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
 72         reqFTP.UseBinary = true;
 73         reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
 74         FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
 75         Stream ftpStream = response.GetResponseStream();
 76         long cl = response.ContentLength;
 77         int bufferSize = 2048;
 78         int readCount;
 79         byte[] buffer = new byte[bufferSize];
 80         readCount = ftpStream.Read(buffer, 0, bufferSize);
 81         while (readCount > 0)
 82         {
 83           outputStream.Write(buffer, 0, readCount);
 84           readCount = ftpStream.Read(buffer, 0, bufferSize);
 85         }
 86         ftpStream.Close();
 87         outputStream.Close();
 88         response.Close();
 89       }
 90       catch (Exception ex)
 91       {
 92         Insert_Standard_ErrorLog.Insert("FtpHelper", "Download Error --> " + ex.Message);
 93       }
 94     }
 95     /// <summary>
 96     /// 删除文件
 97     /// </summary>
 98     /// <param name="fileName"></param>
 99     public void Delete(string fileName)
100     {
101       try
102       {
103         string uri = ftpURI + fileName;
104         FtpWebRequest reqFTP;
105         reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
106         reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
107         reqFTP.KeepAlive = false;
108         reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
109         string result = String.Empty;
110         FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
111         long size = response.ContentLength;
112         Stream datastream = response.GetResponseStream();
113         StreamReader sr = new StreamReader(datastream);
114         result = sr.ReadToEnd();
115         sr.Close();
116         datastream.Close();
117         response.Close();
118       }
119       catch (Exception ex)
120       {
121         Insert_Standard_ErrorLog.Insert("FtpHelper", "Delete Error --> " + ex.Message + "  文件名:" + fileName);
122       }
123     }
124     /// <summary>
125     /// 删除文件夹
126     /// </summary>
127     /// <param name="folderName"></param>
128     public void RemoveDirectory(string folderName)
129     {
130       try
131       {
132         string uri = ftpURI + folderName;
133         FtpWebRequest reqFTP;
134         reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
135         reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
136         reqFTP.KeepAlive = false;
137         reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory;
138         string result = String.Empty;
139         FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
140         long size = response.ContentLength;
141         Stream datastream = response.GetResponseStream();
142         StreamReader sr = new StreamReader(datastream);
143         result = sr.ReadToEnd();
144         sr.Close();
145         datastream.Close();
146         response.Close();
147       }
148       catch (Exception ex)
149       {
150         Insert_Standard_ErrorLog.Insert("FtpHelper", "Delete Error --> " + ex.Message + "  文件名:" + folderName);
151       }
152     }
153     /// <summary>
154     /// 获取当前目录下明细(包含文件和文件夹)
155     /// </summary>
156     /// <returns></returns>
157     public string[] GetFilesDetailList()
158     {
159       string[] downloadFiles;
160       try
161       {
162         StringBuilder result = new StringBuilder();
163         FtpWebRequest ftp;
164         ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI));
165         ftp.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
166         ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
167         WebResponse response = ftp.GetResponse();
168         StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
169         //while (reader.Read() > 0)
170         //{
171         //}
172         string line = reader.ReadLine();
173         //line = reader.ReadLine();
174         //line = reader.ReadLine();
175         while (line != null)
176         {
177           result.Append(line);
178           result.Append("
");
179           line = reader.ReadLine();
180         }
181         result.Remove(result.ToString().LastIndexOf("
"), 1);
182         reader.Close();
183         response.Close();
184         return result.ToString().Split('
');
185       }
186       catch (Exception ex)
187       {
188         downloadFiles = null;
189         Insert_Standard_ErrorLog.Insert("FtpHelper", "GetFilesDetailList Error --> " + ex.Message);
190         return downloadFiles;
191       }
192     }
193     /// <summary>
194     /// 获取当前目录下文件列表(仅文件)
195     /// </summary>
196     /// <returns></returns>
197     public string[] GetFileList(string mask)
198     {
199       string[] downloadFiles;
200       StringBuilder result = new StringBuilder();
201       FtpWebRequest reqFTP;
202       try
203       {
204         reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI));
205         reqFTP.UseBinary = true;
206         reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
207         reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
208         WebResponse response = reqFTP.GetResponse();
209         StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
210         string line = reader.ReadLine();
211         while (line != null)
212         {
213           if (mask.Trim() != string.Empty && mask.Trim() != "*.*")
214           {
215             string mask_ = mask.Substring(0, mask.IndexOf("*"));
216             if (line.Substring(0, mask_.Length) == mask_)
217             {
218               result.Append(line);
219               result.Append("
");
220             }
221           }
222           else
223           {
224             result.Append(line);
225             result.Append("
");
226           }
227           line = reader.ReadLine();
228         }
229         result.Remove(result.ToString().LastIndexOf('
'), 1);
230         reader.Close();
231         response.Close();
232         return result.ToString().Split('
');
233       }
234       catch (Exception ex)
235       {
236         downloadFiles = null;
237         if (ex.Message.Trim() != "远程服务器返回错误: (550) 文件不可用(例如,未找到文件,无法访问文件)。")
238         {
239           Insert_Standard_ErrorLog.Insert("FtpHelper", "GetFileList Error --> " + ex.Message.ToString());
240         }
241         return downloadFiles;
242       }
243     }
244     /// <summary>
245     /// 获取当前目录下所有的文件夹列表(仅文件夹)
246     /// </summary>
247     /// <returns></returns>
248     public string[] GetDirectoryList()
249     {
250       string[] drectory = GetFilesDetailList();
251       string m = string.Empty;
252       foreach (string str in drectory)
253       {
254         int dirPos = str.IndexOf("<DIR>");
255         if (dirPos > 0)
256         {
257           /*判断 Windows 风格*/
258           m += str.Substring(dirPos + 5).Trim() + "
";
259         }
260         else if (str.Trim().Substring(0, 1).ToUpper() == "D")
261         {
262           /*判断 Unix 风格*/
263           string dir = str.Substring(54).Trim();
264           if (dir != "." && dir != "..")
265           {
266             m += dir + "
";
267           }
268         }
269       }
270       char[] n = new char[] { '
' };
271       return m.Split(n);
272     }
273     /// <summary>
274     /// 判断当前目录下指定的子目录是否存在
275     /// </summary>
276     /// <param name="RemoteDirectoryName">指定的目录名</param>
277     public bool DirectoryExist(string RemoteDirectoryName)
278     {
279       string[] dirList = GetDirectoryList();
280       foreach (string str in dirList)
281       {
282         if (str.Trim() == RemoteDirectoryName.Trim())
283         {
284           return true;
285         }
286       }
287       return false;
288     }
289     /// <summary>
290     /// 判断当前目录下指定的文件是否存在
291     /// </summary>
292     /// <param name="RemoteFileName">远程文件名</param>
293     public bool FileExist(string RemoteFileName)
294     {
295       string[] fileList = GetFileList("*.*");
296       foreach (string str in fileList)
297       {
298         if (str.Trim() == RemoteFileName.Trim())
299         {
300           return true;
301         }
302       }
303       return false;
304     }
305     /// <summary>
306     /// 创建文件夹
307     /// </summary>
308     /// <param name="dirName"></param>
309     public void MakeDir(string dirName)
310     {
311       FtpWebRequest reqFTP;
312       try
313       {
314         // dirName = name of the directory to create.
315         reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + dirName));
316         reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
317         reqFTP.UseBinary = true;
318         reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
319         FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
320         Stream ftpStream = response.GetResponseStream();
321         ftpStream.Close();
322         response.Close();
323       }
324       catch (Exception ex)
325       {
326         Insert_Standard_ErrorLog.Insert("FtpHelper", "MakeDir Error --> " + ex.Message);
327       }
328     }
329     /// <summary>
330     /// 获取指定文件大小
331     /// </summary>
332     /// <param name="filename"></param>
333     /// <returns></returns>
334     public long GetFileSize(string filename)
335     {
336       FtpWebRequest reqFTP;
337       long fileSize = 0;
338       try
339       {
340         reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + filename));
341         reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
342         reqFTP.UseBinary = true;
343         reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
344         FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
345         Stream ftpStream = response.GetResponseStream();
346         fileSize = response.ContentLength;
347         ftpStream.Close();
348         response.Close();
349       }
350       catch (Exception ex)
351       {
352         Insert_Standard_ErrorLog.Insert("FtpHelper", "GetFileSize Error --> " + ex.Message);
353       }
354       return fileSize;
355     }
356     /// <summary>
357     /// 改名
358     /// </summary>
359     /// <param name="currentFilename"></param>
360     /// <param name="newFilename"></param>
361     public void ReName(string currentFilename, string newFilename)
362     {
363       FtpWebRequest reqFTP;
364       try
365       {
366         reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + currentFilename));
367         reqFTP.Method = WebRequestMethods.Ftp.Rename;
368         reqFTP.RenameTo = newFilename;
369         reqFTP.UseBinary = true;
370         reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
371         FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
372         Stream ftpStream = response.GetResponseStream();
373         ftpStream.Close();
374         response.Close();
375       }
376       catch (Exception ex)
377       {
378         Insert_Standard_ErrorLog.Insert("FtpHelper", "ReName Error --> " + ex.Message);
379       }
380     }
381     /// <summary>
382     /// 移动文件
383     /// </summary>
384     /// <param name="currentFilename"></param>
385     /// <param name="newFilename"></param>
386     public void MovieFile(string currentFilename, string newDirectory)
387     {
388       ReName(currentFilename, newDirectory);
389     }
390     /// <summary>
391     /// 切换当前目录
392     /// </summary>
393     /// <param name="DirectoryName"></param>
394     /// <param name="IsRoot">true 绝对路径   false 相对路径</param>
395     public void GotoDirectory(string DirectoryName, bool IsRoot)
396     {
397       if (IsRoot)
398       {
399         ftpRemotePath = DirectoryName;
400       }
401       else
402       {
403         ftpRemotePath += DirectoryName + "/";
404       }
405       ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";
406     }
407     /// <summary>
408     /// 删除订单目录
409     /// </summary>
410     /// <param name="ftpServerIP">FTP 主机地址</param>
411     /// <param name="folderToDelete">FTP 用户名</param>
412     /// <param name="ftpUserID">FTP 用户名</param>
413     /// <param name="ftpPassword">FTP 密码</param>
414     public static void DeleteOrderDirectory(string ftpServerIP, string folderToDelete, string ftpUserID, string ftpPassword)
415     {
416       try
417       {
418         if (!string.IsNullOrEmpty(ftpServerIP) && !string.IsNullOrEmpty(folderToDelete) && !string.IsNullOrEmpty(ftpUserID) && !string.IsNullOrEmpty(ftpPassword))
419         {
420           FtpHelper fw = new FtpHelper(ftpServerIP, folderToDelete, ftpUserID, ftpPassword);
421           //进入订单目录
422           fw.GotoDirectory(folderToDelete, true);
423           //获取规格目录
424           string[] folders = fw.GetDirectoryList();
425           foreach (string folder in folders)
426           {
427             if (!string.IsNullOrEmpty(folder) || folder != "")
428             {
429               //进入订单目录
430               string subFolder = folderToDelete + "/" + folder;
431               fw.GotoDirectory(subFolder, true);
432               //获取文件列表
433               string[] files = fw.GetFileList("*.*");
434               if (files != null)
435               {
436                 //删除文件
437                 foreach (string file in files)
438                 {
439                   fw.Delete(file);
440                 }
441               }
442               //删除冲印规格文件夹
443               fw.GotoDirectory(folderToDelete, true);
444               fw.RemoveDirectory(folder);
445             }
446           }
447           //删除订单文件夹
448           string parentFolder = folderToDelete.Remove(folderToDelete.LastIndexOf('/'));
449           string orderFolder = folderToDelete.Substring(folderToDelete.LastIndexOf('/') + 1);
450           fw.GotoDirectory(parentFolder, true);
451           fw.RemoveDirectory(orderFolder);
452         }
453         else
454         {
455           throw new Exception("FTP 及路径不能为空!");
456         }
457       }
458       catch (Exception ex)
459       {
460         throw new Exception("删除订单时发生错误,错误信息为:" + ex.Message);
461       }
462     }
463   }
464   public class Insert_Standard_ErrorLog
465   {
466     public static void Insert(string x, string y)
467     {
468     }
469   }
View Code
原文地址:https://www.cnblogs.com/swtool/p/5299771.html