天天看點

ftp操作類,ftp上傳,下載下傳,建立目錄,檢查檔案存在,删除檔案

using System;

 using System.IO;

 using System.Net;

 using System.Text;

 using System.Diagnostics;

 using System.Text.RegularExpressions;

 using System.Web;



 namespace IS.Common

 {

     /// <summary>

     /// ftp操作類,ftp上傳,下載下傳,建立目錄,檢查檔案存在,删除檔案

     /// </summary>

     public class Ftp

     {

         /// <summary>

         /// 從ftp上下載下傳檔案

         /// </summary>

         /// <param name="filePath">下載下傳到本地的檔案路徑</param>

         /// <param name="FileSrc">ftp源檔案夾</param>

         /// <param name="fileName">下載下傳後的檔案名</param>

         /// <param name="ftpServerIP"></param>

         /// <param name="ftpUserName"></param>

         /// <param name="ftpPwd"></param>

         public static void Download(string filePath, string FileSrc, string fileName, string ftpServerIP, string ftpUserName, string ftpPwd)

         {

             if (!Directory.Exists(filePath))

             {

                 Directory.CreateDirectory(filePath);

             }

             using (FileStream OutputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create))

             {

                 FtpWebRequest ReqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + FileSrc));



                 ReqFTP.Method = WebRequestMethods.Ftp.DownloadFile;

                 ReqFTP.UseBinary = true;

                 ReqFTP.Credentials = new NetworkCredential(ftpUserName, ftpPwd);

                 using (FtpWebResponse response = (FtpWebResponse)ReqFTP.GetResponse())

                 {

                     using (Stream FtpStream = response.GetResponseStream())

                     {

                         long Cl = response.ContentLength;

                         int bufferSize = 2048;

                         int readCount;



                         byte[] buffer = new byte[bufferSize];

                         readCount = FtpStream.Read(buffer, 0, bufferSize);

                         while (readCount > 0)

                         {

                             OutputStream.Write(buffer, 0, readCount);

                             readCount = FtpStream.Read(buffer, 0, bufferSize);

                         }

                         FtpStream.Close();

                     }

                     response.Close();

                 }

                 OutputStream.Close();

             }



         }

         /// <summary>

         /// 從伺服器上傳檔案到FTP上

         /// </summary>

         /// <param name="sFileDstPath">源檔案夾名稱</param>

         /// <param name="FolderName">ftp伺服器的目标檔案夾</param>

         /// <param name="ftpServerIP">ftp ip</param>

         /// <param name="ftpUserName">使用者名</param>

         /// <param name="ftpPwd">密碼</param>

         public static void UploadSmall(string sFileDstPath, string FolderName, string ftpServerIP, string ftpUserName, string ftpPwd)

         {



             FileInfo fileInf = new FileInfo(sFileDstPath);

             FtpWebRequest reqFTP;

             reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + FolderName + "/" + fileInf.Name));



             reqFTP.Credentials = new NetworkCredential(ftpUserName, ftpPwd);

             reqFTP.KeepAlive = false;

             reqFTP.Method = WebRequestMethods.Ftp.UploadFile;

             reqFTP.UseBinary = true;

             reqFTP.ContentLength = fileInf.Length;

             int buffLength = 2048;

             byte[] buff = new byte[buffLength];



             int contentLen;

             using (FileStream fs = fileInf.OpenRead())

             {

                 using (Stream strm = reqFTP.GetRequestStream())

                 {

                     contentLen = fs.Read(buff, 0, buffLength);

                     while (contentLen != 0)

                     {

                         strm.Write(buff, 0, contentLen);

                         contentLen = fs.Read(buff, 0, buffLength);

                     }

                     strm.Close();

                 }

                 fs.Close();

             }



         }

         

         /// <summary>

         /// 删除FTP上的檔案

         /// </summary>

         /// <param name="IName">要删除的檔案數組</param>

         /// <param name="FolderName">要删除檔案所在的ftp檔案夾</param>

         /// <param name="ftpServerIP"></param>

         /// <param name="ftpUserName"></param>

         /// <param name="ftpPwd"></param>

         public static void DeleteFtpFile(string[] IName, string FolderName, string ftpServerIP, string ftpUserName, string ftpPwd)

         {

             foreach (string ImageName in IName)

             {

                 string[] FileList = GetFileList(FolderName, ftpServerIP, ftpUserName, ftpPwd);

                 for (int i = 0; i < FileList.Length; i++)

                 {

                     string Name = FileList[i].ToString();

                     if (Name == ImageName)

                     {

                         FtpWebRequest ReqFTP;



                         ReqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + FolderName + "/" + ImageName));



                         ReqFTP.Credentials = new NetworkCredential(ftpUserName, ftpPwd);

                         ReqFTP.KeepAlive = false;

                         ReqFTP.Method = WebRequestMethods.Ftp.DeleteFile;

                         ReqFTP.UseBinary = true;



                         using (FtpWebResponse Response = (FtpWebResponse)ReqFTP.GetResponse())

                         {

                             long size = Response.ContentLength;

                             using (Stream datastream = Response.GetResponseStream())

                             {

                                 using (StreamReader sr = new StreamReader(datastream))

                                 {

                                     sr.ReadToEnd();

                                     sr.Close();

                                 }

                                 datastream.Close();

                             }

                             Response.Close();

                         }

                     }

                 }



             }



         }

         /// <summary>

         /// 檢查檔案是否存在

         /// </summary>

         /// <param name="FolderName">ftp檔案夾</param>

         /// <param name="ftpServerIP"></param>

         /// <param name="ftpUserName"></param>

         /// <param name="ftpPwd"></param>

         /// <returns></returns>

         public static string[] GetFileList(string FolderName, string ftpServerIP, string ftpUserName, string ftpPwd)

         {

             string[] downloadFiles;

             StringBuilder result = new StringBuilder();

             FtpWebRequest reqFTP;

             try

             {

                 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + FolderName + "/"));



                 reqFTP.UseBinary = true;

                 reqFTP.Credentials = new NetworkCredential(ftpUserName, ftpPwd);

                 reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;



                 WebResponse response = reqFTP.GetResponse();

                 StreamReader reader = new StreamReader(response.GetResponseStream());



                 string line = reader.ReadLine();

                 while (line != null)

                 {

                     result.Append(line);

                     result.Append("\n");

                     line = reader.ReadLine();

                 }

                 // to remove the trailing '\n'        

                 result.Remove(result.ToString().LastIndexOf('\n'), 1);

                 reader.Close();

                 response.Close();

                 return result.ToString().Split('\n');

             }

             catch (Exception ex)

             {

                 downloadFiles = null;

                 return downloadFiles;

             }

         }

         

         /// <summary>

         /// 從用戶端上傳檔案到FTP上

         /// </summary>

         /// <param name="sFilePath">用戶端檔案上傳類</param>

         /// <param name="filename">ftp檔案名</param>

         /// <param name="FolderName">ftp檔案夾</param>

         /// <param name="ftpServerIP"></param>

         /// <param name="ftpUserName"></param>

         /// <param name="ftpPwd"></param>

         public static void UploadFtp(HttpPostedFile sFilePath, string filename, string FolderName, string ftpServerIP, string ftpUserName, string ftpPwd)

         {

             //擷取的伺服器路徑

             //FileInfo fileInf = new FileInfo(sFilePath);

             FtpWebRequest reqFTP;

             reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + FolderName + "/" + filename));

             reqFTP.Credentials = new NetworkCredential(ftpUserName, ftpPwd);

             reqFTP.KeepAlive = false;

             reqFTP.Method = WebRequestMethods.Ftp.UploadFile;

             reqFTP.UseBinary = true;

             reqFTP.ContentLength = sFilePath.ContentLength;

             //設定緩存

             int buffLength = 2048;

             byte[] buff = new byte[buffLength];

             int contentLen;

             using (Stream fs = sFilePath.InputStream)

             {

                 using (Stream strm = reqFTP.GetRequestStream())

                 {

                     contentLen = fs.Read(buff, 0, buffLength);

                     while (contentLen != 0)

                     {

                         strm.Write(buff, 0, contentLen);

                         contentLen = fs.Read(buff, 0, buffLength);

                     }

                     strm.Close();

                 }

                 fs.Close();

             }



         }

         

         /// <summary>

         /// 建立目錄

         /// </summary>

         /// <param name="FolderName">ftp目錄</param>

         /// <param name="ftpServerIP"></param>

         /// <param name="ftpUserName"></param>

         /// <param name="ftpPwd"></param>

         public static void CreateDirectory(string FolderName, string ftpServerIP, string ftpUserName, string ftpPwd)

         {

             //建立日期目錄

             try

             {

                 FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" +  FolderName));



                 reqFTP.UseBinary = true;

                 reqFTP.Credentials = new NetworkCredential(ftpUserName, ftpPwd);

                 reqFTP.KeepAlive = false;

                 reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;



                 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();

             }

             catch

             {

                 

             }

         }



         private static Regex regexName = new Regex(@"[^\s]*$", RegexOptions.Compiled);

         /// <summary>

         /// 檢查日期目錄和檔案是否存在

         /// </summary>

         /// <param name="FolderName">檔案(夾)名</param>

         /// <param name="ftpServerIP"></param>

         /// <param name="ftpUserName"></param>

         /// <param name="ftpPwd"></param>

         /// <returns></returns>

         public static bool CheckFileOrPath(string FolderName, string ftpServerIP, string ftpUserName, string ftpPwd)

         {

             //檢查一下日期目錄是否存在

             FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/"));



             reqFTP.UseBinary = true;

             reqFTP.Credentials = new NetworkCredential(ftpUserName, ftpPwd);

             reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;

             Stream stream = reqFTP.GetResponse().GetResponseStream();

             using (StreamReader sr = new StreamReader(stream))

             {

                 string line = sr.ReadLine();

                 while (!string.IsNullOrEmpty(line))

                 {

                     GroupCollection gc = regexName.Match(line).Groups;

                     if (gc.Count != 1)

                     {

                         throw new ApplicationException("FTP 傳回的字串格式不正确");

                     }



                     string path = gc[0].Value;

                     if (path == FolderName)

                     {

                         return true;

                     }



                     line = sr.ReadLine();

                 }

             }

             return false;

         }


     }

 }      

繼續閱讀