C # Ftphelper supports multi-level file upload and download

Source: Internet
Author: User
Tags ftp connection

Find a lot of code on the Internet always feel unable to meet the existing needs, such as multi-level folders, one-time upload all the files at different levels. Add your own changes to the code you find online. Now posted out to everyone hope that a little help to everyone. Welcome to the fault, progress with each other

    <summary>///FTP Help class///</summary> public class Ftphelper {#region field Stri        Ng Ftpuri;        String Ftpuserid;        String Ftpserverip;        String FTPPassword;        String Ftpremotepath; #endregion//<summary>///Connect FTP server///</summary>//<param name= "Ftpse Rverip "&GT;FTP connection address </param>///<param Name=" Ftpremotepath "> Specify the current directory after successful FTP connection, if not specified, the default is the root directory </param&gt          ;          <param name= "Ftpuserid" > Username </param>//<param name= "FTPPassword" > Password </param> Public Ftphelper (String Ftpserverip, String Ftpremotepath, String Ftpuserid, String FTPPassword) {This            . Ftpserverip = Ftpserverip;            This.ftpremotepath = Ftpremotepath;            This.ftpuserid = Ftpuserid;            This.ftppassword = FTPPassword;        This.ftpuri = "ftp://" + Ftpserverip + "/" + Ftpremotepath + "/"; }        /// <summary>//upload///</summary> public void Upload (string filename, string ftpremote            Path) {FileInfo fileinf = new FileInfo (filename);            FtpWebRequest reqftp;            Reqftp = (ftpwebrequest) ftpwebrequest.create (new Uri (Ftpuri + "/" + Ftpremotepath + "/" + Fileinf.name));            Reqftp.credentials = new NetworkCredential (Ftpuserid, FTPPassword);            Reqftp.method = WebRequestMethods.Ftp.UploadFile;            Reqftp.keepalive = false;            Reqftp.usebinary = true;            Reqftp.contentlength = Fileinf.length;            int bufflength = 2048;            byte[] buff = new Byte[bufflength];            int Contentlen;            FileStream fs = Fileinf.openread ();                try {Stream strm = Reqftp.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 (); } catch (Exception ex) {throw new Exception (ex).            Message); }}///<summary>//download///</summary> public void Download (string LocalPath, String ftpremotepath) {try {FileStream outputstream = new Filestr                EAM (LocalPath, FileMode.Create);                FtpWebRequest reqftp;                Reqftp = (ftpwebrequest) ftpwebrequest.create (new Uri (Ftpuri + ftpremotepath));                Reqftp.credentials = new NetworkCredential (Ftpuserid, FTPPassword);                Reqftp.method = WebRequestMethods.Ftp.DownloadFile;                Reqftp.usebinary = true;                FtpWebResponse response = (ftpwebresponse) reqftp.getresponse (); Stream FtpStream = Response. GetResponseStream (); Long cl = Response.                ContentLength;                int buffersize = 2048;                int readcount;                byte[] buffer = new Byte[buffersize];                Readcount = ftpstream.read (buffer, 0, buffersize);                    while (Readcount > 0) {outputstream.write (buffer, 0, readcount);                Readcount = ftpstream.read (buffer, 0, buffersize);                } ftpstream.close ();                Outputstream.close (); Response.            Close (); } catch (Exception ex) {throw new Exception (ex).            Message); }}///<summary>///delete file///</summary> public void Delete (string f                Ilename) {try {ftpwebrequest reqftp;                Reqftp = (ftpwebrequest) ftpwebrequest.create (new Uri (Ftpuri + fileName)); Reqftp.credentials = new NeTworkcredential (Ftpuserid, FTPPassword);                Reqftp.method = WebRequestMethods.Ftp.DeleteFile;                Reqftp.keepalive = false;                string result = String.Empty;                FtpWebResponse response = (ftpwebresponse) reqftp.getresponse (); Long size = Response.                ContentLength; Stream datastream = Response.                GetResponseStream ();                StreamReader sr = new StreamReader (datastream); result = Sr.                ReadToEnd (); Sr.                Close (); DataStream.                Close (); Response.            Close (); } catch (Exception ex) {throw new Exception (ex).            Message); }}///<summary>///Get the current directory details (including files and folders)///</summary> public Strin                G[] Getfilesdetaillist () {try {StringBuilder result = new StringBuilder ();                FtpWebRequest FTP; FTP =(FtpWebRequest)                Ftpwebrequest.create (New Uri (Ftpuri));                Ftp.credentials = new NetworkCredential (Ftpuserid, FTPPassword);                Ftp.method = WebRequestMethods.Ftp.ListDirectoryDetails;                WebResponse response = Ftp.getresponse (); StreamReader reader = new StreamReader (response.                GetResponseStream ()); String line = reader.                ReadLine (); line = reader.                ReadLine (); 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) {throw new Exception (ex).            Message); }        }        /<summary>///Get a list of FTP files (including folders)///</summary> public string[] Getalllist (String u            RL) {list<string> List = new list<string> ();            FtpWebRequest req = (ftpwebrequest) webrequest.create (new Uri (Ftpuri + URL)); Req.            Credentials = new NetworkCredential (Ftpuserid, FTPPassword); Req.            Method = WebRequestMethods.Ftp.ListDirectory; Req.            Usebinary = true; Req.            Usepassive = true; try {using (ftpwebresponse res = (ftpwebresponse) req. GetResponse ()) {using (StreamReader sr = new StreamReader (res).                        GetResponseStream ())) {string S; while (s = Sr. ReadLine ()) = null) {list.                        ADD (s);  }}}} catch (Exception ex) {              Throw (ex); } return list.        ToArray (); }///<summary>///Get a list of files in the current directory (excluding folders)///</summary> public string[] Getfi            Lelist (string url) {StringBuilder result = new StringBuilder ();            FtpWebRequest reqftp;                try {reqftp = (ftpwebrequest) ftpwebrequest.create (new Uri (Ftpuri + URL));                Reqftp.usebinary = true;                Reqftp.credentials = new NetworkCredential (Ftpuserid, FTPPassword);                Reqftp.method = WebRequestMethods.Ftp.ListDirectoryDetails;                WebResponse response = Reqftp.getresponse (); StreamReader reader = new StreamReader (response.                GetResponseStream ()); String line = reader.                ReadLine (); while (line! = null) {if (line. IndexOf ("<DIR>") = =-1) {result. Append (REGEX.MATCH (line, @ "[\s]+ [\s]+], regexoptions.ignorecase).                        Value.split (") [1]); Result.                    Append ("\ n"); } line = reader.                ReadLine (); } if (result. Length > 0) {result. Remove (result. ToString ().                LastIndexOf (' \ n '), 1); } reader.                Close (); Response.            Close ();            } catch (Exception ex) {throw (ex); } return result. ToString ().        Split (' \ n '); }///<summary>///Get all file path recursion (including subdirectory files)///</summary>//<param name= "dir" &G            t;</param>//<returns></returns> public string[] Getallfilelist (string dir) {            list<string> list = new list<string> ();            string[] filelist = Getalllist (dir); for (int i = 0; i < filelist. Length;               i++) { var filepath = filelist[i];                Determine if the file is bool IsTrue = fileexist (dir + "\ \" + filepath); if (istrue) {list.                Add (dir + "\" + filepath);                    } else {var dir2 = dir + "\ \" + filepath;                    var list1 = getallfilelist (DIR2); for (int j = 0; J < List1. Length; J + +) {list.                    ADD (List1[j]); }}} return list.        ToArray (); }///<summary>//Determine if the file specified in the current directory exists///</summary>//<param name= "Remote FileName "> Remote file name </param> public bool FileExist (string remotefilename) {var request = (            FtpWebRequest) WebRequest.Create (Ftpuri + remotefilename); Request.            Credentials = new NetworkCredential (Ftpuserid, FTPPassword); Request. Method =WebRequestMethods.Ftp.GetFileSize; try {ftpwebresponse response = (ftpwebresponse) request.            GetResponse (); } catch (WebException ex) {ftpwebresponse response = (FtpWebResponse) ex.                Response; if (response.                StatusCode = = ftpstatuscode.actionnottakenfileunavailable) {return false;        }} return true; }///<summary>//detection directory exists///</summary>//<param name= "dir" >&        lt;/param>//<returns>false not present, true exists </returns> private bool Directoryisexist (string dir)            {FtpWebRequest reqftp = (ftpwebrequest) ftpwebrequest.create (new Uri (Ftpuri + dir));            Reqftp.credentials = new NetworkCredential (Ftpuserid, FTPPassword);            Reqftp.method = WebRequestMethods.Ftp.PrintWorkingDirectory; Reqftp.usebinary = tRue                try {ftpwebresponse response = (ftpwebresponse) reqftp.getresponse (); Response.                Close ();            return true; } catch (Exception ex) {string e = ex.                Message;            return false; }}///<summary>//Create Folder///</summary> public void maked            IR (string dirName) {FtpWebRequest reqftp;                try {reqftp = (ftpwebrequest) ftpwebrequest.create (new Uri (Ftpuri + dirName));                Reqftp.method = WebRequestMethods.Ftp.MakeDirectory;                Reqftp.usebinary = true;                Reqftp.credentials = new NetworkCredential (Ftpuserid, FTPPassword);                FtpWebResponse response = (ftpwebresponse) reqftp.getresponse (); Stream FtpStream = Response.                GetResponseStream ();                Ftpstream.close (); Response.Close (); } catch (Exception ex) {}}//<summary>//Get the specified file size///&L            T;/summary> Public long GetFileSize (string filename) {FtpWebRequest reqftp;            Long fileSize = 0;                try {reqftp = (ftpwebrequest) ftpwebrequest.create (new Uri (Ftpuri + filename));                Reqftp.method = WebRequestMethods.Ftp.GetFileSize;                Reqftp.usebinary = true;                Reqftp.credentials = new NetworkCredential (Ftpuserid, FTPPassword);                FtpWebResponse response = (ftpwebresponse) reqftp.getresponse (); Stream FtpStream = Response.                GetResponseStream (); FileSize = Response.                ContentLength;                Ftpstream.close (); Response.            Close ();        } catch (Exception ex) {} return fileSize; }//<summary>//Change file name// </summary> public void ReName (string currentfilename, String newfilename) {FtpWebRequest            Reqftp;                try {reqftp = (ftpwebrequest) ftpwebrequest.create (new Uri (Ftpuri + currentfilename));                Reqftp.method = WebRequestMethods.Ftp.Rename;                Reqftp.renameto = NewFileName;                Reqftp.usebinary = true;                Reqftp.credentials = new NetworkCredential (Ftpuserid, FTPPassword);                FtpWebResponse response = (ftpwebresponse) reqftp.getresponse (); Stream FtpStream = Response.                GetResponseStream ();                Ftpstream.close (); Response.            Close (); } catch (Exception ex) {}}//<summary>//Mobile File//</s ummary> public void Moviefile (string currentfilename, String newdirectory) {ReName (currentf        Ilename, newdirectory); }//<suMmary>////switch current directory///</summary>//<param name= "IsRoot" >true: Absolute path false: relative path &L            t;/param> public void Gotodirectory (string directoryname, bool IsRoot) {if (IsRoot)            {Ftpremotepath = directoryname;            } else {Ftpremotepath + = directoryname + "/";        } Ftpuri = "ftp://" + Ftpserverip + "/" + Ftpremotepath + "/"; }    }


C # Ftphelper supports multi-level file upload and download

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.