【C#】FtpHelper對伺服器檔案實現讀寫操作的執行個體詳解

來源:互聯網
上載者:User
這篇文章主要為大家詳細介紹了FtpHelper實現ftp伺服器檔案讀寫操作,具有一定的參考價值,感興趣的小夥伴們可以參考一下

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.IO; using System.Threading;using System.Configuration;  namespace FtpSyn {   public class FtpHelper   {     //基本設定 ftp://400:ZOina2017@192.168.10.17/400backup     static private string path = @"ftp://" + ConfigurationManager.AppSettings["FtpServerIP"].ToString() + "/";  //目標路徑     static private string ftpip = ConfigurationManager.AppSettings["FtpServerIP"].ToString();  //ftp IP地址     static private string username = ConfigurationManager.AppSettings["FtpUserName"].ToString();  //ftp使用者名稱     static private string password = ConfigurationManager.AppSettings["FtpPassWord"].ToString();  //ftp密碼         //擷取ftp上面的檔案和檔案夾     public static string[] GetFileList(string dir)     {       string[] downloadFiles;       StringBuilder result = new StringBuilder();       FtpWebRequest request;       try       {         request = (FtpWebRequest)FtpWebRequest.Create(new Uri(path + dir));         request.UseBinary = true;         request.Credentials = new NetworkCredential(username, password);//設定使用者名稱和密碼         request.Method = WebRequestMethods.Ftp.ListDirectory;         request.UseBinary = true;         request.UsePassive = false; //選擇主動還是被動模式 , 這句要加上的。         request.KeepAlive = false;//一定要設定此屬性,否則一次性下載多個檔案的時候,會出現異常。         WebResponse response = request.GetResponse();         StreamReader reader = new StreamReader(response.GetResponseStream());          string line = reader.ReadLine();         while (line != null)         {           result.Append(line);           result.Append("\n");           line = reader.ReadLine();         }          result.Remove(result.ToString().LastIndexOf('\n'), 1);         reader.Close();         response.Close();         return result.ToString().Split('\n');       }       catch (Exception ex)       {         LogHelper.writeErrorLog("擷取ftp上面的檔案和檔案夾:" + ex.Message);         downloadFiles = null;         return downloadFiles;       }     }      /// <summary>     /// 從ftp伺服器上擷取檔案並將內容全部轉換成string返回     /// </summary>     /// <param name="fileName"></param>     /// <param name="dir"></param>     /// <returns></returns>     public static string GetFileStr(string fileName, string dir)     {       FtpWebRequest reqFTP;       try       {         reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path + dir + "/" + fileName));         reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;         reqFTP.UseBinary = true;         reqFTP.Credentials = new NetworkCredential(username, password);         reqFTP.UsePassive = false; //選擇主動還是被動模式 , 這句要加上的。         reqFTP.KeepAlive = false;//一定要設定此屬性,否則一次性下載多個檔案的時候,會出現異常。         FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();         Stream ftpStream = response.GetResponseStream();         StreamReader reader = new StreamReader(ftpStream);         string fileStr = reader.ReadToEnd();          reader.Close();         ftpStream.Close();         response.Close();         return fileStr;       }       catch (Exception ex)       {         LogHelper.writeErrorLog("擷取ftp檔案並讀取內容失敗:" + ex.Message);         return null;       }     }       /// <summary>     /// 擷取檔案大小     /// </summary>     /// <param name="file">ip伺服器下的相對路徑</param>     /// <returns>檔案大小</returns>     public static int GetFileSize(string file)     {       StringBuilder result = new StringBuilder();       FtpWebRequest request;       try       {         request = (FtpWebRequest)FtpWebRequest.Create(new Uri(path + file));         request.UseBinary = true;         request.Credentials = new NetworkCredential(username, password);//設定使用者名稱和密碼         request.Method = WebRequestMethods.Ftp.GetFileSize;          int dataLength = (int)request.GetResponse().ContentLength;          return dataLength;       }       catch (Exception ex)       {         Console.WriteLine("擷取檔案大小出錯:" + ex.Message);         return -1;       }     }      /// <summary>     /// 檔案上傳     /// </summary>     /// <param name="filePath">原路徑(絕對路徑)包括檔案名稱</param>     /// <param name="objPath">目標檔案夾:伺服器下的相對路徑 不填為根目錄</param>     public static void FileUpLoad(string filePath,string objPath="")     {       try       {         string url = path;         if(objPath!="")           url += objPath + "/";         try         {            FtpWebRequest reqFTP = null;           //待上傳的檔案 (全路徑)           try           {             FileInfo fileInfo = new FileInfo(filePath);             using (FileStream fs = fileInfo.OpenRead())             {               long length = fs.Length;               reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(url + fileInfo.Name));                //設定串連到FTP的帳號密碼               reqFTP.Credentials = new NetworkCredential(username, password);               //佈建要求完成後是否保持串連               reqFTP.KeepAlive = false;               //指定執行命令               reqFTP.Method = WebRequestMethods.Ftp.UploadFile;               //指定資料轉送類型               reqFTP.UseBinary = true;                using (Stream stream = reqFTP.GetRequestStream())               {                 //設定緩衝大小                 int BufferLength = 5120;                 byte[] b = new byte[BufferLength];                 int i;                 while ((i = fs.Read(b, 0, BufferLength)) > 0)                 {                   stream.Write(b, 0, i);                 }                 Console.WriteLine("上傳檔案成功");               }             }           }           catch (Exception ex)           {             Console.WriteLine("上傳檔案失敗錯誤為" + ex.Message);           }           finally           {            }         }         catch (Exception ex)         {           Console.WriteLine("上傳檔案失敗錯誤為" + ex.Message);         }         finally         {          }       }       catch (Exception ex)       {         Console.WriteLine("上傳檔案失敗錯誤為" + ex.Message);       }     }          /// <summary>     /// 刪除檔案     /// </summary>     /// <param name="fileName">伺服器下的相對路徑 包括檔案名稱</param>     public static void DeleteFileName(string fileName)     {       try       {         FileInfo fileInf = new FileInfo(ftpip +""+ fileName);         string uri = path + fileName;         FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));         // 指定資料轉送類型         reqFTP.UseBinary = true;         // ftp使用者名稱和密碼         reqFTP.Credentials = new NetworkCredential(username, password);         // 預設為true,串連不會被關閉         // 在一個命令之後被執行         reqFTP.KeepAlive = false;         // 指定執行什麼命令         reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;         FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();         response.Close();       }       catch (Exception ex)       {         Console.WriteLine("刪除檔案出錯:" + ex.Message);       }     }          /// <summary>     /// 建立目錄 上一級必須先存在     /// </summary>     /// <param name="dirName">伺服器下的相對路徑</param>     public static void MakeDir(string dirName)     {       try       {         string uri = path + dirName;         FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));         // 指定資料轉送類型         reqFTP.UseBinary = true;         // ftp使用者名稱和密碼         reqFTP.Credentials = new NetworkCredential(username, password);         reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;         FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();         response.Close();       }       catch (Exception ex)       {         Console.WriteLine("建立目錄出錯:" + ex.Message);       }     }          /// <summary>     /// 刪除目錄 上一級必須先存在     /// </summary>     /// <param name="dirName">伺服器下的相對路徑</param>     public static void DelDir(string dirName)     {       try       {         string uri = path + dirName;         FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));         // ftp使用者名稱和密碼         reqFTP.Credentials = new NetworkCredential(username, password);         reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory;         FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();         response.Close();       }       catch (Exception ex)       {         Console.WriteLine("刪除目錄出錯:" + ex.Message);       }     }      /// <summary>     /// 從ftp伺服器上獲得資料夾清單     /// </summary>     /// <param name="RequedstPath">伺服器下的相對路徑</param>     /// <returns></returns>     public static List<string> GetDirctory(string RequedstPath)     {       List<string> strs = new List<string>();       try       {         string uri = path + RequedstPath;  //目標路徑 path為伺服器位址         FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));         // ftp使用者名稱和密碼         reqFTP.Credentials = new NetworkCredential(username, password);         reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;         WebResponse response = reqFTP.GetResponse();         StreamReader reader = new StreamReader(response.GetResponseStream());//中文檔案名稱          string line = reader.ReadLine();         while (line != null)         {           if (line.Contains("<DIR>"))           {             string msg = line.Substring(line.LastIndexOf("<DIR>")+5).Trim();             strs.Add(msg);           }           line = reader.ReadLine();         }         reader.Close();         response.Close();         return strs;       }       catch (Exception ex)       {         Console.WriteLine("擷取目錄出錯:" + ex.Message);       }       return strs;     }      /// <summary>     /// 從ftp伺服器上獲得檔案清單     /// </summary>     /// <param name="RequedstPath">伺服器下的相對路徑</param>     /// <returns></returns>     public static List<string> GetFile(string RequedstPath)     {       List<string> strs = new List<string>();       try       {         string uri = path + RequedstPath;  //目標路徑 path為伺服器位址         FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));         // ftp使用者名稱和密碼         reqFTP.Credentials = new NetworkCredential(username, password);         reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;         WebResponse response = reqFTP.GetResponse();         StreamReader reader = new StreamReader(response.GetResponseStream());//中文檔案名稱          string line = reader.ReadLine();         while (line != null)         {           if (!line.Contains("<DIR>"))           {             string msg = line.Substring(39).Trim();             strs.Add(msg);           }           line = reader.ReadLine();         }         reader.Close();         response.Close();         return strs;       }       catch (Exception ex)       {         Console.WriteLine("擷取檔案出錯:" + ex.Message);       }       return strs;     }      } }
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.