C#操作FTP總結

 本文是對FTP相關操作,例如新建/刪除目錄、新建/刪除文件、獲取文件/目錄列表等的總結,方便日后調用。

  其實C#操作FTP和操作本地文件/目錄差不多,尤其是對動作而言,因為它們都是文件或目錄,區別在于FTP可以是遠程的文件或目錄等,所以需要建立一個連接,當然由于是對FTP的請求,所以會要求從本地發起一個FtpWebRequest,當然這個請求中包含一些設置,例如:請求連接的信用憑證、數據的傳輸格式、以及請求的FTP動作等等,FTP服務器接收到這個請求后就會返回一個FtpWebResponse了。本來微軟已經提供了操作FTP的一些方法,都在System.Net命名空間下,但是感覺用起來還是不是很方便,所以自己又總結了一下,權且當作是對一個簡單地封裝吧,方便以后再使用的時候可以拿來就用。

  由于這些方法都比較簡單,而且每個方法我都加了中文注釋,所以在此就不再贅述和分別描述了,直接上代碼。

using System.Collections;using System.Collections.Generic;using UnityEngine;using UnityEngine.UI;using System.Net;using System.IO;using System;using System.Text;using System.Configuration;using System.Linq;public class FTP_test : MonoBehaviour{ private static string url = "ftp://192.168.1.25/"; private static string userName = "mao"; private static string passWord = "mao"; // private static string pathName = ""; // Listlist; // string[] dir; void Start() { // DeleteFileOnServer(url, "2.txt"); // list = GetDirctory(url, "txt"); // Debug.Log("txt文件夾中的文件個數====" + list.Count); // dir = GetFileList(); // Debug.Log("Ftp服務器中文件總數====" + dir.Length); // int count = GetFileSize("android.txt"); // Debug.Log(count); // FileUpLoad("C:\\Users\\User\\Desktop\\doc\\民機AR檢查記錄軟件詳細設計V1.0.doc", "txt"); // MakeDir("tex/tesss"); DelDir("txt/tex"); } /// /// 刪除文件

? ? /// ///ftp的ip地址? ? ///刪除文件的名字? ? public static void DeleteFileOnServer(string serverUri, string pathName)? ? {? ? ? ? try? ? ? ? {? ? ? ? ? ? string urlPath = serverUri + pathName;? ? ? ? ? ? FtpWebRequest request = (FtpWebRequest)WebRequest.Create(urlPath);? ? ? ? ? ? //指定數據傳輸類型? ? ? ? ? ? request.UseBinary = true;? ? ? ? ? ? //用戶名密碼? ? ? ? ? ? request.Credentials = new NetworkCredential(userName, passWord);? ? ? ? ? ? // 默認為true,連接不會被關閉? ? ? ? ? ? // 在一個命令之后被執行? ? ? ? ? ? request.KeepAlive = false;? ? ? ? ? ? //指定執行什么命令? ? ? ? ? ? request.Method = WebRequestMethods.Ftp.DeleteFile;? ? ? ? ? ? FtpWebResponse response = (FtpWebResponse)request.GetResponse();? ? ? ? ? ? response.Close();? ? ? ? }? ? ? ? catch (Exception ex)? ? ? ? {? ? ? ? ? ? Debug.Log("刪除文件出錯" + ex.Message);? ? ? ? }? ? }? ? ///? ? /// 從ftp服務器上獲得文件夾列表

? ? /// ///服務器下的相對路徑? ? ///public static ListGetDirctory(string url, string RequedstPath)? ? {? ? ? ? Liststrs = new List();? ? ? ? try? ? ? ? {? ? ? ? ? ? string uri = url + 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(""))? ? ? ? ? ? ? ? {? ? ? ? ? ? ? ? ? ? string msg = line.Substring(line.LastIndexOf("") + 5).Trim();? ? ? ? ? ? ? ? ? ? strs.Add(msg);? ? ? ? ? ? ? ? }? ? ? ? ? ? ? ? line = reader.ReadLine();? ? ? ? ? ? }? ? ? ? ? ? reader.Close();? ? ? ? ? ? response.Close();? ? ? ? ? ? return strs;? ? ? ? }? ? ? ? catch (Exception ex)? ? ? ? {? ? ? ? ? ? Console.WriteLine("獲取目錄出錯:" + ex.Message);? ? ? ? }? ? ? ? return strs;? ? }? ? ///? ? /// 獲取ftp服務器上的文件和文件夾列表

? ? /// ///public static string[] GetFileList()? ? {? ? ? ? string[] downloadFiles;? ? ? ? StringBuilder result = new StringBuilder();? ? ? ? FtpWebRequest request;? ? ? ? try? ? ? ? {? ? ? ? ? ? request = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));? ? ? ? ? ? request.UseBinary = true;? ? ? ? ? ? request.Credentials = new NetworkCredential(userName, passWord);//設置用戶名和密碼? ? ? ? ? ? request.Method = WebRequestMethods.Ftp.ListDirectory;? ? ? ? ? ? request.UseBinary = true;? ? ? ? ? ? WebResponse response = request.GetResponse();? ? ? ? ? ? StreamReader reader = new StreamReader(response.GetResponseStream());? ? ? ? ? ? string line = reader.ReadLine();? ? ? ? ? ? Debug.Log("============開始讀取內容==+ line==========");? ? ? ? ? ? while (line != null)? ? ? ? ? ? {? ? ? ? ? ? ? ? result.Append(line);? ? ? ? ? ? ? ? result.Append("\n");? ? ? ? ? ? ? ? line = reader.ReadLine();? ? ? ? ? ? }? ? ? ? ? ? // 刪除拖尾“\n”? ? ? ? ? ? result.Remove(result.ToString().LastIndexOf('\n'), 1);? ? ? ? ? ? reader.Close();? ? ? ? ? ? response.Close();? ? ? ? ? ? return result.ToString().Split('\n');? ? ? ? }? ? ? ? catch (Exception ex)? ? ? ? {? ? ? ? ? ? Debug.Log("獲取ftp上面的文件和文件夾:" + ex.Message);? ? ? ? ? ? downloadFiles = null;? ? ? ? ? ? return downloadFiles;? ? ? ? }? ? }? ? ///? ? /// 獲取文件大小

? ? /// ///ip服務器下的相對路徑? ? ///文件大小public static int GetFileSize(string file)? ? {? ? ? //? StringBuilder result = new StringBuilder();? ? ? ? FtpWebRequest request;? ? ? ? try? ? ? ? {? ? ? ? ? ? request = (FtpWebRequest)FtpWebRequest.Create(new Uri(url + file));? ? ? ? ? ? Debug.Log(url + 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)? ? ? ? {? ? ? ? ? ? Debug.Log("獲取文件大小出錯:" + ex.Message);? ? ? ? ? ? return -1;? ? ? ? }? ? }? ? ///? ? /// 文件上傳

? ? /// ///原路徑(絕對路徑)包括文件名? ? ///目標文件夾:服務器下的相對路徑 不填為根目錄? ? public static void FileUpLoad(string filePath, string objPath = "")? ? {? ? ? ? try? ? ? ? {? ? ? ? ? ? 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);? ? ? ? ? ? ? ? ? ? ? ? ? ? }? ? ? ? ? ? ? ? ? ? ? ? ? ? Debug.Log("上傳文件成功");? ? ? ? ? ? ? ? ? ? ? ? }? ? ? ? ? ? ? ? ? ? }? ? ? ? ? ? ? ? }? ? ? ? ? ? ? ? catch (Exception ex)? ? ? ? ? ? ? ? {? ? ? ? ? ? ? ? ? ? Debug.Log("上傳文件失敗錯誤為" + ex.Message);? ? ? ? ? ? ? ? }? ? ? ? ? ? ? ? finally? ? ? ? ? ? ? ? {? ? ? ? ? ? ? ? }? ? ? ? ? ? }? ? ? ? ? ? catch (Exception ex)? ? ? ? ? ? {? ? ? ? ? ? ? ? Debug.Log("上傳文件失敗錯誤為" + ex.Message);? ? ? ? ? ? }? ? ? ? ? ? finally? ? ? ? ? ? {? ? ? ? ? ? }? ? ? ? }? ? ? ? catch (Exception ex)? ? ? ? {? ? ? ? ? ? Debug.Log("上傳文件失敗錯誤為" + ex.Message);? ? ? ? }? ? }? ? ///? ? /// 新建目錄 上一級必須先存在

? ? /// ///服務器下的相對路徑? ? public static void MakeDir(string dirName)? ? {? ? ? ? try? ? ? ? {? ? ? ? ? ? string uri = url + 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);? ? ? ? }? ? }? ? ///? ? /// 刪除目錄 上一級必須先存在

? ? /// ///服務器下的相對路徑? ? public static void DelDir(string dirName)? ? {? ? ? ? try? ? ? ? {? ? ? ? ? ? string uri = url + dirName;? ? ? ? ? ? Debug.Log(uri);? ? ? ? ? ? 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();? ? ? ? ? ? Debug.Log(response);? ? ? ? ? ? response.Close();? ? ? ? }? ? ? ? catch (Exception ex)? ? ? ? {? ? ? ? ? ? Console.WriteLine("刪除目錄出錯:" + ex.Message);? ? ? ? }? ? }? ? ///? ? /// 從ftp服務器上獲得文件列表

? ? /// ///服務器下的相對路徑? ? ///public static ListGetFile(string RequedstPath)? ? {? ? ? ? Liststrs = new List();? ? ? ? try? ? ? ? {? ? ? ? ? ? string uri = url + 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(""))

? ? ? ? ? ? ? ? {

? ? ? ? ? ? ? ? ? ? string msg = line.Substring(39).Trim();

? ? ? ? ? ? ? ? ? ? strs.Add(msg);

? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? line = reader.ReadLine();

? ? ? ? ? ? }

? ? ? ? ? ? reader.Close();

? ? ? ? ? ? response.Close();

? ? ? ? ? ? return strs;

? ? ? ? }

? ? ? ? catch (Exception ex)

? ? ? ? {

? ? ? ? ? ? Debug.Log("獲取文件出錯:" + ex.Message);

? ? ? ? }

? ? ? ? return strs;

? ? }

}

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,908評論 6 541
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,324評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,018評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,675評論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,417評論 6 412
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,783評論 1 329
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,779評論 3 446
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,960評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,522評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,267評論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,471評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,009評論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,698評論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,099評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,386評論 1 294
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,204評論 3 398
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,436評論 2 378

推薦閱讀更多精彩內容

  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,823評論 18 139
  • 1、連接FTP服務器 /// /// 連接FTP服務器 /// /// FTP連接地址 /// 指定FTP連接成功...
    Solchen閱讀 352評論 0 0
  • 讀樸槿惠這本書,有三個原因,其一,在高中時劉寒梅老師在講人物隱忍例子的時候,提到過這位韓國史上第一位女總統,這或許...
    泡泡兒seven閱讀 715評論 2 4
  • 在最近,內心一直在糾結。我為什么而存在?人生目標是什么?我很困惑。因為我不知道自己的人生到底需要什么,如...
    鹿鹿無畏閱讀 681評論 0 51
  • 每天我們都在等。 等一會兒在做,等一會兒在說,等一會兒在吃。等一會兒之后,很可能這件事就會被擱淺。 我一直想不明白...
    你你你你你你呀閱讀 211評論 0 0