程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C#開辟教程之ftp操作辦法整頓

C#開辟教程之ftp操作辦法整頓

編輯:C#入門知識

C#開辟教程之ftp操作辦法整頓。本站提示廣大學習愛好者:(C#開辟教程之ftp操作辦法整頓)文章只能為提供參考,不一定能成為您想要的結果。以下是C#開辟教程之ftp操作辦法整頓正文


1.比來項目開辟觸及到ftp操作。發明FtpWebRequest類有些操作很費事,

例如創立目次只能創立一級目次,多級就掉敗。刪除目次只能刪除最初一級的空目次。異樣下載也是。

故寫下贊助類便利應用。

2.挪用辦法展現,

var ftp = new FtpHelper("111.111.111.111", "xxxxxxx", "xxxxxx");//初始化ftp,創立ftp對象
ftp.uploadFile("F:\\wms.zip","aaa//bbb");//參數1當地文件,參數2:ftp的目次
ftp.delDirAll("aaa");//參數 要刪除的目次的 途徑
ftp.downloadAllFile("aaa","F:\\myfile");//參數1:要下載的目次,參數2,保留到當地的目次

3.FtpHelper 代碼。後續再彌補解釋

1.異常辦法拜托,經由過程Lamda拜托同一處置異常,便利改寫。加了個拜托便利掌握異常輸入

2.遞歸查找一切目次存入list,然後依據 level排序,從最末級開端遍歷刪除

3.ftp的目次列表比擬怪,臨時用截取字符串的獲得 目次或文件

/// <summary>
/// ftp贊助類
/// </summary>
public class FtpHelper
{
private string ftpHostIP { get; set; }
private string username { get; set; }
private string password { get; set; }
private string ftpURI { get { return $@"ftp://{ftpHostIP}/"; } }
/// <summary>
/// 初始化ftp參數
/// </summary>
/// <param name="ftpHostIP">ftp主機IP</param>
/// <param name="username">ftp賬戶</param>
/// <param name="password">ftp暗碼</param>
public FtpHelper(string ftpHostIP, string username, string password)
{
this.ftpHostIP = ftpHostIP;
this.username = username;
this.password = password;
}
/// <summary>
/// 異常辦法拜托,經由過程Lamda拜托同一處置異常,便利改寫
/// </summary>
/// <param name="method">以後履行的辦法</param>
/// <param name="action"></param>
/// <returns></returns>
private bool MethodInvoke(string method, Action action)
{
if (action != null)
{
try
{
action();
//Logger.Write2File($@"FtpHelper.{method}:履行勝利");
FluentConsole.Red.Line($@"FtpHelper.{method}:履行勝利");
return true;
}
catch (Exception ex)
{
FluentConsole.Red.Line($@"FtpHelper.{method}:履行掉敗", ex.ToString());
// Logger.Write2File(action.GetType().Name, ex.ToString());
return false;
}
}
else
{
return false;
}
}
/// <summary>
/// 異常辦法拜托,經由過程Lamda拜托同一處置異常,便利改寫
/// </summary>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="method"></param>
/// <param name="func"></param>
/// <returns></returns>
private T MethodInvoke<T>(string method, Func<T> func)
{
if (func != null)
{
try
{
FluentConsole.Red.Line($@"FtpHelper.{method}:履行勝利");
return func();
//Logger.Write2File($@"FtpHelper.{method}:履行勝利");
}
catch (Exception ex)
{
FluentConsole.Red.Line($@"FtpHelper.{method}:履行掉敗:{ex}");
// Logger.Write2File($@"FtpHelper.{method}:履行掉敗", ex.ToString());
return default(T);
}
}
else
{
return default(T);
}
}
private FtpWebRequest GetRequest(string URI)
{
//依據辦事器信息FtpWebRequest創立類的對象
FtpWebRequest result = (FtpWebRequest)WebRequest.Create(URI);
result.Credentials = new NetworkCredential(username, password);
result.KeepAlive = false;
result.UsePassive = false;
result.UseBinary = true;
return result;
}
/// <summary> 上傳文件</summary>
/// <param name="filePath">須要上傳的文件</param>
/// <param name="targetDir">目的途徑</param>
public bool uploadFile(string filePath, string dirName = "")
{
FileInfo fileInfo = new FileInfo(filePath);
if (dirName != "") makeDir(dirName);
string uri = Path.Combine(ftpURI, dirName, fileInfo.Name);
return MethodInvoke($@"uploadFile({filePath},{dirName})", () =>
{
FtpWebRequest ftp = GetRequest(uri);
ftp.Method = WebRequestMethods.Ftp.UploadFile;
ftp.ContentLength = fileInfo.Length;
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
using (FileStream fs = fileInfo.OpenRead())
{
using (Stream strm = ftp.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="dirName"></param>
/// <param name="currentDir"></param>
/// <returns></returns>
public bool checkDir(string dirName, string currentDir = "")
{
string uri = Path.Combine(ftpURI, currentDir);
return MethodInvoke($@"checkDir({dirName}{currentDir})", () =>
{
FtpWebRequest ftp = GetRequest(uri);
ftp.UseBinary = true;
ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
Stream stream = ftp.GetResponse().GetResponseStream();
using (StreamReader sr = new StreamReader(stream))
{
string line = sr.ReadLine();
while (!string.IsNullOrEmpty(line))
{
string dir = string.Empty;
if (line.IndexOf("<DIR>") > -1)
{
if (line.Substring(line.IndexOf("<DIR>") + 5).Trim() == dirName)
return true;
}
line = sr.ReadLine();
}
sr.Close();
}
stream.Close();
return false;
});
}
/// <summary>
/// 獲得以後目次下的目次及文件
/// </summary>
/// param name="ftpfileList"></param>
/// <param name="dirName"></param>
/// <returns></returns>
public List<Ftpfile> getFtpFile(string dirName)
{
var ftpfileList = new List<Ftpfile>();
string uri = Path.Combine(ftpURI, dirName);
return MethodInvoke($@"getFile({dirName})", () =>
{
var a = new List<List<string>>();
FtpWebRequest ftp = GetRequest(uri);
ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
Stream stream = ftp.GetResponse().GetResponseStream();
using (StreamReader sr = new StreamReader(stream))
{
string line = sr.ReadLine();
while (!string.IsNullOrEmpty(line))
{
ftpfileList.Add(new Ftpfile { isDir = line.IndexOf("<DIR>") > -1, name = line.Substring(39).Trim(),path= Path.Combine(dirName, line.Substring(39).Trim()) });
line = sr.ReadLine();
}
sr.Close();
}
return ftpfileList;
});
}
/// <summary>
/// 獲得目次下的一切目次及文件包含其子目次和子文件
/// </summary>
/// param name="ftpfileList"></param>
/// <param name="dirName"></param>
/// <returns></returns>
public List<Ftpfile> getAllFtpFile(List<Ftpfile> ftpfileList, string dirName, int level = 0)
{
var flist = new List<Ftpfile>();
string uri = Path.Combine(ftpURI, dirName);
return MethodInvoke($@"getFile({dirName})", () =>
{
var a = new List<List<string>>();
FtpWebRequest ftp = GetRequest(uri);
ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
Stream stream = ftp.GetResponse().GetResponseStream();
using (StreamReader sr = new StreamReader(stream))
{
string line = sr.ReadLine();
while (!string.IsNullOrEmpty(line))
{
flist.Add(new Ftpfile { isDir = line.IndexOf("<DIR>") > -1, name = line.Substring(39).Trim(), level = level, path= Path.Combine(dirName ,line.Substring(39).Trim()) });
ftpfileList.Add(new Ftpfile { isDir = line.IndexOf("<DIR>") > -1, name = line.Substring(39).Trim(), level = level, path = Path.Combine(dirName, line.Substring(39).Trim()) });
line = sr.ReadLine();
}
sr.Close();
}
var nflist = flist.Where(x => x.isDir).ToList();
if (nflist.Count == 0)
return ftpfileList;
else
return getAllFtpFile(ftpfileList, Path.Combine(dirName, nflist.First().name), level + 1);
});
}
/// </summary>
/// 在ftp辦事器上創立指定目次,父目次不存在則創立
/// </summary>
/// <param name="dirName">創立的目次稱號</param>
public bool makeDir(string dirName)
{
var dirs = dirName.Split('\\').ToList();//針對多級目次朋分
string currentDir = string.Empty;
return MethodInvoke($@"makeDir({dirName})", () =>
{
foreach (var dir in dirs)
{
if (!checkDir(dir, currentDir))//檢討目次不存在則創立
{
currentDir = Path.Combine(currentDir, dir);
string uri = Path.Combine(ftpURI, currentDir);
FtpWebRequest ftp = GetRequest(uri);
ftp.Method = WebRequestMethods.Ftp.MakeDirectory;
FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
response.Close();
}
else
{
currentDir = Path.Combine(currentDir, dir);
}
}
});
}
/// <summary> 
/// 刪除單個文件
/// </summary>
/// <param name="filePath"></param>
public bool delFile(string filePath)
{
string uri = Path.Combine(ftpURI, filePath);
return MethodInvoke($@"deleteFile({filePath})", () =>
{
FtpWebRequest ftp = GetRequest(uri);
ftp.Method = WebRequestMethods.Ftp.DeleteFile;
FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
response.Close();
});
}
/// <summary> 
/// 刪除最末及空目次
/// </summary>
/// <param name="dirName"></param>
private bool delDir(string dirName)
{
string uri = Path.Combine(ftpURI, dirName);
return MethodInvoke($@"delDir({dirName})", () =>
{
FtpWebRequest ftp = GetRequest(uri);
ftp.Method = WebRequestMethods.Ftp.RemoveDirectory;
FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
response.Close();
});
}
/// <summary> 刪除目次或許其目次下一切的文件 </summary>
/// <param name="dirName">目次稱號</param>
/// <param name="ifDelSub">能否刪除目次下一切的文件</param>
public void delDirAll(string dirName)
{
var dlist = getAllFtpFile(new List<Ftpfile>(),dirName);
dlist.OrderByDescending(x => x.level);//降序分列,先刪除末及文件或空目次
string uri = Path.Combine(ftpURI, dirName);
MethodInvoke($@"delDirAll({dirName})", () =>
{
foreach (var item in dlist)
{
if (item.isDir)//斷定是目次挪用目次的刪除辦法
delDir(item.path);
else
delFile(item.path);
}
});
}
/// <summary>文件重定名 </summary>
/// <param name="currentFilename">以後稱號</param>
/// <param name="newFilename">重定名稱號</param>
/// <param name="currentFilename">地點的目次</param>
public bool Rename(string currentFilename, string newFilename, string dirName = "")
{
string uri = Path.Combine(ftpURI, dirName, currentFilename);
return MethodInvoke($@"Rename({currentFilename},{newFilename},{dirName})", () =>
{
FtpWebRequest ftp = GetRequest(uri);
ftp.Method = WebRequestMethods.Ftp.Rename;
ftp.RenameTo = newFilename;
FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
response.Close();
});
}
/// <summary>
/// 下載單個文件
/// </summary>
/// <param name="ftpFilePath">從ftp要下載的文件途徑</param>
/// <param name="localDir">下載至當地途徑</param>
/// <param name="filename">文件名</param>
public bool downloadFile(string ftpFilePath, string saveDir, string filename)
{
string tmpname = Guid.NewGuid().ToString();
string uri = Path.Combine(ftpURI, ftpFilePath);
return MethodInvoke($@"downloadFile({ftpFilePath},{saveDir},{filename})", () =>
{
if (!Directory.Exists(saveDir)) Directory.CreateDirectory(saveDir);
FtpWebRequest ftp = GetRequest(uri);
ftp.Method = WebRequestMethods.Ftp.DownloadFile;
using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (FileStream fs = new FileStream(Path.Combine(saveDir, filename), FileMode.CreateNew))
{
byte[] buffer = new byte[2048];
int read = 0;
do
{
read = responseStream.Read(buffer, 0, buffer.Length);
fs.Write(buffer, 0, read);
} while (!(read == 0));
responseStream.Close();
fs.Flush();
fs.Close();
}
responseStream.Close();
}
response.Close();
}
});
}
/// <summary> 
/// 從FTP下載全部文件夾 
/// </summary> 
/// <param name="dirName">FTP文件夾途徑</param> 
/// <param name="saveDir">保留的當地文件夾途徑</param> 
public void downloadAllFile(string dirName, string saveDir)
{
MethodInvoke($@"downloadAllFile({dirName},{saveDir})", () =>
{
List<Ftpfile> files = getFtpFile(dirName);
if (!Directory.Exists(saveDir))
{
Directory.CreateDirectory(saveDir);
}
foreach (var f in files)
{
if (f.isDir) //文件夾,遞歸查詢 
{
downloadAllFile(Path.Combine(dirName + f.name), Path.Combine(saveDir + f.name));
}
else //文件,直接下載 
{
downloadFile(Path.Combine(dirName + f.name), saveDir, f.name);
}
}
});
}
}
public class Ftpfile
{
public int level { get; set; } = 0;
public bool isDir { get; set; }
public string name { get; set; }
public string path { get; set; } = "";
}

以上所述是小編給年夜家引見的C#開辟教程之ftp操作辦法整頓,願望對年夜家有所贊助,假如年夜家有任何疑問請給我留言,小編會實時答復年夜家的。在此也異常感激年夜家對網站的支撐!

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