本文是對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;
? ? }
}