FtpHelper實(shí)現(xiàn)ftp服務(wù)器文件讀寫操作(C#)
最近做了一個(gè)項(xiàng)目,需要讀取ftp服務(wù)器上的文件,于是參考了網(wǎng)上提供的一些幫組方法,使用過程中,出現(xiàn)一些小細(xì)節(jié)問題,于是本人做了一些修改,拿來分享一下
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
{
//基本設(shè)置 ftp://400:ZOina2017@192.168.10.17/400backup
static private string path = @"ftp://" + ConfigurationManager.AppSettings["FtpServerIP"].ToString() + "/"; //目標(biāo)路徑
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);//設(shè)置用戶名和密碼
request.Method = WebRequestMethods.Ftp.ListDirectory;
request.UseBinary = true;
request.UsePassive = false; //選擇主動(dòng)還是被動(dòng)模式 , 這句要加上的。
request.KeepAlive = false;//一定要設(shè)置此屬性,否則一次性下載多個(gè)文件的時(shí)候,會(huì)出現(xiàn)異常。
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服務(wù)器上獲取文件并將內(nèi)容全部轉(zhuǎn)換成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; //選擇主動(dòng)還是被動(dòng)模式 , 這句要加上的。
reqFTP.KeepAlive = false;//一定要設(shè)置此屬性,否則一次性下載多個(gè)文件的時(shí)候,會(huì)出現(xiàn)異常。
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文件并讀取內(nèi)容失?。? + ex.Message);
return null;
}
}
/// <summary>
/// 獲取文件大小
/// </summary>
/// <param name="file">ip服務(wù)器下的相對(duì)路徑</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);//設(shè)置用戶名和密碼
request.Method = WebRequestMethods.Ftp.GetFileSize;
int dataLength = (int)request.GetResponse().ContentLength;
return dataLength;
}
catch (Exception ex)
{
Console.WriteLine("獲取文件大小出錯(cuò):" + ex.Message);
return -1;
}
}
/// <summary>
/// 文件上傳
/// </summary>
/// <param name="filePath">原路徑(絕對(duì)路徑)包括文件名</param>
/// <param name="objPath">目標(biāo)文件夾:服務(wù)器下的相對(duì)路徑 不填為根目錄</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));
//設(shè)置連接到FTP的帳號(hào)密碼
reqFTP.Credentials = new NetworkCredential(username, password);
//設(shè)置請(qǐng)求完成后是否保持連接
reqFTP.KeepAlive = false;
//指定執(zhí)行命令
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
//指定數(shù)據(jù)傳輸類型
reqFTP.UseBinary = true;
using (Stream stream = reqFTP.GetRequestStream())
{
//設(shè)置緩沖大小
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("上傳文件失敗錯(cuò)誤為" + ex.Message);
}
finally
{
}
}
catch (Exception ex)
{
Console.WriteLine("上傳文件失敗錯(cuò)誤為" + ex.Message);
}
finally
{
}
}
catch (Exception ex)
{
Console.WriteLine("上傳文件失敗錯(cuò)誤為" + ex.Message);
}
}
/// <summary>
/// 刪除文件
/// </summary>
/// <param name="fileName">服務(wù)器下的相對(duì)路徑 包括文件名</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));
// 指定數(shù)據(jù)傳輸類型
reqFTP.UseBinary = true;
// ftp用戶名和密碼
reqFTP.Credentials = new NetworkCredential(username, password);
// 默認(rèn)為true,連接不會(huì)被關(guān)閉
// 在一個(gè)命令之后被執(zhí)行
reqFTP.KeepAlive = false;
// 指定執(zhí)行什么命令
reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
response.Close();
}
catch (Exception ex)
{
Console.WriteLine("刪除文件出錯(cuò):" + ex.Message);
}
}
/// <summary>
/// 新建目錄 上一級(jí)必須先存在
/// </summary>
/// <param name="dirName">服務(wù)器下的相對(duì)路徑</param>
public static void MakeDir(string dirName)
{
try
{
string uri = path + dirName;
FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
// 指定數(shù)據(jù)傳輸類型
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("創(chuàng)建目錄出錯(cuò):" + ex.Message);
}
}
/// <summary>
/// 刪除目錄 上一級(jí)必須先存在
/// </summary>
/// <param name="dirName">服務(wù)器下的相對(duì)路徑</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("刪除目錄出錯(cuò):" + ex.Message);
}
}
/// <summary>
/// 從ftp服務(wù)器上獲得文件夾列表
/// </summary>
/// <param name="RequedstPath">服務(wù)器下的相對(duì)路徑</param>
/// <returns></returns>
public static List<string> GetDirctory(string RequedstPath)
{
List<string> strs = new List<string>();
try
{
string uri = path + RequedstPath; //目標(biāo)路徑 path為服務(wù)器地址
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("獲取目錄出錯(cuò):" + ex.Message);
}
return strs;
}
/// <summary>
/// 從ftp服務(wù)器上獲得文件列表
/// </summary>
/// <param name="RequedstPath">服務(wù)器下的相對(duì)路徑</param>
/// <returns></returns>
public static List<string> GetFile(string RequedstPath)
{
List<string> strs = new List<string>();
try
{
string uri = path + RequedstPath; //目標(biāo)路徑 path為服務(wù)器地址
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("獲取文件出錯(cuò):" + ex.Message);
}
return strs;
}
}
}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持我們。
欄 目:C#教程
本文標(biāo)題:FtpHelper實(shí)現(xiàn)ftp服務(wù)器文件讀寫操作(C#)
本文地址:http://m.jygsgssxh.com/a1/C_jiaocheng/5816.html
您可能感興趣的文章
- 01-10C#實(shí)現(xiàn)txt定位指定行完整實(shí)例
- 01-10WinForm實(shí)現(xiàn)仿視頻播放器左下角滾動(dòng)新聞效果的方法
- 01-10C#實(shí)現(xiàn)清空回收站的方法
- 01-10C#實(shí)現(xiàn)讀取注冊(cè)表監(jiān)控當(dāng)前操作系統(tǒng)已安裝軟件變化的方法
- 01-10C#實(shí)現(xiàn)多線程下載文件的方法
- 01-10C#實(shí)現(xiàn)Winform中打開網(wǎng)頁(yè)頁(yè)面的方法
- 01-10C#實(shí)現(xiàn)遠(yuǎn)程關(guān)閉計(jì)算機(jī)或重啟計(jì)算機(jī)的方法
- 01-10C#自定義簽名章實(shí)現(xiàn)方法
- 01-10C#文件斷點(diǎn)續(xù)傳實(shí)現(xiàn)方法
- 01-10winform實(shí)現(xiàn)創(chuàng)建最前端窗體的方法


閱讀排行
- 1C語言 while語句的用法詳解
- 2java 實(shí)現(xiàn)簡(jiǎn)單圣誕樹的示例代碼(圣誕
- 3利用C語言實(shí)現(xiàn)“百馬百擔(dān)”問題方法
- 4C語言中計(jì)算正弦的相關(guān)函數(shù)總結(jié)
- 5c語言計(jì)算三角形面積代碼
- 6什么是 WSH(腳本宿主)的詳細(xì)解釋
- 7C++ 中隨機(jī)函數(shù)random函數(shù)的使用方法
- 8正則表達(dá)式匹配各種特殊字符
- 9C語言十進(jìn)制轉(zhuǎn)二進(jìn)制代碼實(shí)例
- 10C語言查找數(shù)組里數(shù)字重復(fù)次數(shù)的方法
本欄相關(guān)
- 01-10C#通過反射獲取當(dāng)前工程中所有窗體并
- 01-10關(guān)于ASP網(wǎng)頁(yè)無法打開的解決方案
- 01-10WinForm限制窗體不能移到屏幕外的方法
- 01-10WinForm繪制圓角的方法
- 01-10C#實(shí)現(xiàn)txt定位指定行完整實(shí)例
- 01-10WinForm實(shí)現(xiàn)仿視頻播放器左下角滾動(dòng)新
- 01-10C#停止線程的方法
- 01-10C#實(shí)現(xiàn)清空回收站的方法
- 01-10C#通過重寫Panel改變邊框顏色與寬度的
- 01-10C#實(shí)現(xiàn)讀取注冊(cè)表監(jiān)控當(dāng)前操作系統(tǒng)已
隨機(jī)閱讀
- 01-11Mac OSX 打開原生自帶讀寫NTFS功能(圖文
- 01-11ajax實(shí)現(xiàn)頁(yè)面的局部加載
- 01-10使用C語言求解撲克牌的順子及n個(gè)骰子
- 08-05DEDE織夢(mèng)data目錄下的sessions文件夾有什
- 08-05織夢(mèng)dedecms什么時(shí)候用欄目交叉功能?
- 08-05dedecms(織夢(mèng))副欄目數(shù)量限制代碼修改
- 01-10C#中split用法實(shí)例總結(jié)
- 04-02jquery與jsp,用jquery
- 01-10delphi制作wav文件的方法
- 01-10SublimeText編譯C開發(fā)環(huán)境設(shè)置


