C # Development Tutorial FTP operation method Finishing _c# Tutorial

Source: Internet
Author: User
Tags parent directory readline trim

1. Recent project development involves FTP operations. found that some operations of the FtpWebRequest class are cumbersome,

For example, creating a directory creates only one level of directory, and multiple levels fail. Deleting a directory deletes only the last level of empty directories. Likewise downloads are.

So write down the help class for ease of use.

2. Call method Display,

var ftp = new Ftphelper ("111.111.111.111", "xxxxxxx", "xxxxxx");//Initialize FTP, create FTP object
ftp.uploadfile ("F:\\wms.zip", " AAA//BBB ")//Parameter 1 local file, parameter 2:ftp directory
ftp.deldirall (" AAA ");//The path of the directory to be deleted by the parameter
ftp.downloadallfile (" AAA "," f:\\ MyFile ")//Parameter 1: directory to download, parameter 2, save to local directory

3.FtpHelper code. Follow-up and additional Notes

1. Exception method delegate, through Lamda Delegate unified handling of exceptions, easy to rewrite. A delegate was added to facilitate the control of abnormal output.

2. Recursively find all directories in the list, and then sort by level, starting at the bottom to traverse the deletion

3.ftp directory listing is strange, temporarily using the intercept string to get the directory or file

<summary>///FTP Help class///</summary> public class Ftphelper {private string Ftphostip {get; set;} Priva Te string Username {get; set;} private string Password {get; set;} private string Ftpuri {get-return $@ ' ftp://{ftph ostip}/"; }///<summary>///initialization ftp parameters///</summary>///<param name= "Ftphostip" >ftp host ip</param>///< param name= "username" >ftp account </param>///<param name= "password" >ftp password </param> public ftphelper ( String Ftphostip, string Username, string password) {this.ftphostip = Ftphostip; this.username = username; this.password
= password; ///<summary>///Exception method delegate, which handles exceptions uniformly through LAMDA delegates, facilitates overwriting///</summary>///<param name= "method" > currently executing methods </ param>///<param name= "action" ></param>///<returns></returns> private bool Methodinvoke ( String method, Action action {if (action!= null) {try {action ();//logger.write2file ($@ "ftphelper.{
METHOD}: Successful execution "); Fluentconsole.red.lINE ($@ "ftphelper.{
METHOD}: Successful execution ");
return true; The catch (Exception ex) {FluentConsole.Red.Line ($@) ftphelper.{ Method}: Execution failed, ex.
ToString ()); Logger.write2file (action. GetType (). Name, ex.
ToString ());
return false;
} else {return false;}} <summary>///Exception method delegate, through Lamda Delegate unified handling of exceptions, easy to rewrite///</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) {T ry {FluentConsole.Red.Line ($@) ftphelper.{
METHOD}: Successful execution ");
return func (); Logger.write2file ($@ "ftphelper.{
METHOD}: Successful execution "); The catch (Exception ex) {FluentConsole.Red.Line ($@) ftphelper.{
Method}: Failed to execute: {ex} "); Logger.write2file ($@ "ftphelper.{ Method}: Execution failed, ex.
ToString ());
return default (T);
} else {return default (T);}} Private FtpWebRequest Getrequest (string URI) {//FtpWebRequest creation of class based on server informationObject FtpWebRequest result = (ftpwebrequest) webrequest.create (URI); Result.
Credentials = new NetworkCredential (username, password); Result.
KeepAlive = false; Result.
Usepassive = false; Result.
Usebinary = true;
return result; ///<summary> upload files </summary>///<param name= "FilePath" > Files to be uploaded </param>///<param name= " TargetDir "> Target path </param> public bool UploadFile (string FilePath, String dirname =" ") {FileInfo FileInfo = new Fi
Leinfo (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>///Check for directory presence///</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>///Get the directories and files in the current directory///</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>///get all directories and files in the directory including their subdirectories and subfolders///</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 ($@ "Get
File ({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.
-A (). Name), level + 1);
}); ///</summary>///Create the specified directory on the FTP server, the parent directory does not exist, create///</summary>///<param name= "dirname" > directory name created </ Param> public bool MakeDir (string dirname) {var dirs = dirname.split (' \ '). ToList ()///For multilevel directory split string currentdir = String.
Empty; Return Methodinvoke ($@ "MakeDir ({dirname})", () => {foreach (var dir. dirs) {if (!checkdir (dir, currentdir))/Check directory does not exist
In then create {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>///Delete a single file///</summary>///<param name= "FilePath" ></param> public bool Delfile (string Filep Ath) {string uri = Path.Combine (Ftpuri, FilePath); return Methodinvoke ($@ "DeleteFile ({FilePath})", () => {Ftpwebreque
St FTP = getrequest (URI);
Ftp.method = WebRequestMethods.Ftp.DeleteFile;
FtpWebResponse response = (ftpwebresponse) ftp.getresponse (); Response.
Close ();
}); ///<summary>///Delete the last and empty directories///</summary>///<param name= "dirname" ></param> private bool Deldi R (String dirname) {string uri = Path.Combine (Ftpuri, dirname); return Methodinvoke ($@ "Deldir ({dirname})", () => {FTPW
Ebrequest ftp = getrequest (URI);
Ftp.method = WebRequestMethods.Ftp.RemoveDirectory;
FtpWebResponse response = (ftpwebresponse) ftp.getresponse (); Response.
Close ();
}); ///<summary> Delete directory or all files in its directory </summary>///<param name= "dirname" > directory name </param>///<param Name= "Ifdelsub" > Delete all Files under the directory </param> public void Deldirall (String dirname) {var dlist = getallftpfile (New list<ftpfile> (), dirname);
OrderByDescending (x => x.level);//descending order, first delete the end and file or empty directory string uri = Path.Combine (Ftpuri, dirname); Methodinvoke ($@ "Deldirall ({dirname})", () => {foreach (var item in dlist) {if (Item.isdir)//judgment is the directory call directory deletion method Deldir (ite
M.path);
else Delfile (Item.path);
}
}); ///<summary> File Rename </summary>///<param name= "Currentfilename" > Current name </param>///<param Name= "NewFileName" > Rename name </param>///<param name= "currentfilename" > directory </param> public bool Rename (String currentfilename, String newfilename, String dirname = "") {string uri = Path.Combine (Ftpuri, DirName, Curre
Ntfilename); 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>///Downloads A single file///</summary>///<param name= "Ftpfilepath" > File paths to download from FTP </param>///<param Name= "Localdir" > Download to local path </param>///<param name= "filename" > 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>///Download entire folder from FTP///</summary>///<param name= "dirname" >ftp folder path </param>///
<param name= "Savedir" > Saved local folder path </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)//folder, recursive query {D
Ownloadallfile (Path.Combine (dirname + f.name), Path.Combine (Savedir + f.name));
else//file, download directly {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; s Et public string path {get; set;} = "";}

The above is a small set up to introduce the C # development tutorial of the FTP operation method of sorting, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.