C # Implementing FTP Uploads and downloads

Source: Internet
Author: User
Tags constant definition ftp connection

C # implementing FTP download files

Beginner C # need to use FTP to download files, here to record a bit.

Using system;using system.collections.generic;using system.linq;using system.text;using System.Threading.Tasks;        Using system.net;using system.io;using System.threading;namespace ftputils{class Ftphelper {//default constant definition        private static readonly String rootpath = "/";        private static readonly int defaultreadwritetimeout = 300000;        private static readonly int defaultftpport = 21; #region Set initialization parameters private String host = String.        Empty; public string Host {get {return this.host??? string.            Empty; }} private String username = string.        Empty;            public string Username {get {return this.username; }} private String password = string.        Empty;            public string Password {get {return this.password;        }} IWebProxy proxy = null; Public IWEbproxy Proxy {get {return this.proxy;            } set {this.proxy = value;        }} private int port = Defaultftpport;            public int Port {get {return port;            } set {this.port = value;        }} private bool Enablessl = false;            public bool Enablessl {get {return enablessl;        }} private bool usepassive = true;            public bool Usepassive {get {return usepassive;            } set {this.usepassive = value;        }} private bool usebinary = true;            public bool Userbinary {get {return usebinary;         } set {       This.usebinary = value;        }} private String remotepath = RootPath;            public string RemotePath {get {return remotepath;                } set {string result = RootPath; if (!string. IsNullOrEmpty (value) && value! = rootpath) {result = Path.Combine (Path.Combine ( RootPath, value. TrimStart ('/'). TrimEnd ('/')), "/");            Stitching of the path} This.remotepath = result;        }} private int readwritetimeout = Defaultreadwritetimeout;            public int Readwritetimeout {get {return readwritetimeout;            } set {this.readwritetimeout = value;             }} #endregion #region constructor public ftphelper (string host,string Username, string password) : This (host, username, password, defaultftpport, NULL, FALSE, True, True, Defaultreadwritetimeout) {}//<summary> constructors///</summary>//<param name= "host" > Host name </param>//<param NA Me= "username" > User name </param>//<param name= "password" > Password </param>///<param name= "Por T "> Port number Default 21</param>//<param name=" proxy "> Proxy default no </param>//<param name=" enables SL "> Whether to use SSL by default </param>//<param name=" usebinary "> Use binary </param>//<param name=" Usepassive "> Gets or sets the behavior of the data transfer process for the client application </param>//<param name=" Readwritetimeout "> read/write timeout time default 5min</par Am> public Ftphelper (string host, string username, string password, int port, IWebProxy proxy, bool Enablessl, b Ool Usebinary, bool usepassive, int readwritetimeout) {this.host = host. ToLower (). StartsWith ("ftp://")? Host: "ftp://" + host;            This.username = Username;            This.password = password;            This.port = port;            This.proxy = proxy;            This.enablessl = Enablessl;            This.usebinary = usebinary;            This.usepassive = usepassive;        This.readwritetimeout = Readwritetimeout; } #endregion///<summary>///stitching URL//</summary>//<param name= "hos T "> Hostname </param>//<param name=" RemotePath "> Address </param>///<param name=" FileName "  ; file name </param>////<returns> returns the full url</returns> private string Urlcombine (string host, String RemotePath, String fileName) {string result = new Uri (the new Uri (the new Uri (host). TrimEnd ('/')), RemotePath), FileName).            ToString ();;        return result; }///<summary>//Create a connection///</summary>//<param name= "url" > Address &LT;/PARAM&G        T <Param name= "Method" > Methods </param>//<returns> return Request object </returns> private Ftpwebreques T createconnection (string URL, String method) {FtpWebRequest request = (ftpwebrequest) ftpwebrequest.cre            Ate (new Uri (URL)); Request.            Credentials = new NetworkCredential (This.username, This.password); Request.            Proxy = This.proxy; Request.            KeepAlive = false; Request.            Usebinary = usebinary; Request.            Usepassive = usepassive; Request.            Enablessl = Enablessl; Request.            Method = method;            Console.WriteLine (request);        return request; }///<summary>//Upload files///</summary>//<param name= "LocalFile" > Local Files < /param>//<param name= "remotefilename" > Upload file name </param>//<returns> upload successful return True</ret       Urns> public bool Upload (FileInfo LocalFile, string remotefilename) {     BOOL result = FALSE; if (localfile.exists) {try {string url = urlcombine (Host, Re                    Motepath, Remotefilename);                    FtpWebRequest request = createconnection (URL, WebRequestMethods.Ftp.UploadFile); using (Stream rs = Request.                        GetRequestStream ()) using (FileStream fs = Localfile.openread ()) {                        byte[] buffer = new byte[1024 * 4]; int count = fs. Read (buffer, 0, buffer.                        Length); while (Count > 0) {Rs.                            Write (buffer, 0, count); Count = fs. Read (buffer, 0, buffer.                        Length); } fs.                        Close ();                    result = true; }} catch (WebException ex) {MessageBox.Show (ex). Message);               } return result;        }//Handle local file does not exist return false; }///<summary>///download File///</summary>//<param name= "serverName" > Server file name </param>//<param name= "LocalName" > Need to save local file name </param>//<returns> download successful return TRUE&L            T;/returns> public bool Download (string serverName, String localname) {bool result = false;                using (FileStream fs = new FileStream (LocalName, FileMode.OpenOrCreate)) {try                    {String url = urlcombine (Host, RemotePath, serverName);                    Console.WriteLine (URL);                    FtpWebRequest request = createconnection (URL, WebRequestMethods.Ftp.DownloadFile); Request. Contentoffset = fs.                    Length; using (ftpwebresponse response = (ftpwebresponse) request.                    GetResponse ()){fs. Position = fs.                        Length;                        byte[] buffer = new byte[1024 * 4]; int count = Response. GetResponseStream (). Read (buffer, 0, buffer.                        Length); while (Count > 0) {fs.                            Write (buffer, 0, count); Count = Response. GetResponseStream (). Read (buffer, 0, buffer.                        Length); } response. GetResponseStream ().                    Close ();                } result = true;            } catch (WebException ex) {//Handle exceptions in FTP connection}}        return result; }    }}

Specific FtpWebRequest View documents:
Https://msdn.microsoft.com/zh-cn/library/system.net.ftpwebrequest.usepassive (v=vs.110). aspx

C # Implementing FTP Uploads and downloads

Related Article

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.