程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> FtpHelper實現ftp服務器文件讀寫操作(C#)

FtpHelper實現ftp服務器文件讀寫操作(C#)

編輯:C#入門知識

FtpHelper實現ftp服務器文件讀寫操作(C#)。本站提示廣大學習愛好者:(FtpHelper實現ftp服務器文件讀寫操作(C#))文章只能為提供參考,不一定能成為您想要的結果。以下是FtpHelper實現ftp服務器文件讀寫操作(C#)正文


最近做了一個項目,需要讀取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:[email protected]/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;
     }
   
   }
 }

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved