C # FTP upload and download code

Source: Internet
Author: User

C # FTP upload and download code

Using System; using System. Collections. Generic; using System. Linq; using System. Text; using System. Net; using System. IO; namespace JianKunKing. Common. Ftp {////// Download and upload files through ftp ///Public static class FileUpDownload {# region variable attributes ////// Ftp Server ip ///Public static string FtpServerIP = string. Empty ;////// Specify the Ftp user name ///Public static string FtpUserID = string. Empty ;////// Ftp specifies the User Password ///Public static string FtpPassword = string. Empty; # endregion # region downloads files from the FTP server and specifies the local path and local file name ////// Download the file from the FTP server and specify the local path and local file name //////Remote File Name ///Save the local file name (including the path )///Whether to enable authentication (false: allows anonymous download )///Report Progress processing (first parameter: total size, second parameter: current progress )///
 
  
Download successful?
 Public static bool FtpDownload (string remoteFileName, string localFileName, bool ifCredential, Action
 
  
UpdateProgress = null) {FtpWebRequest reqFTP, ftpsize; Stream ftpStream = null; FtpWebResponse response = null; FileStream outputStream = null; try {outputStream = new FileStream (localFileName, FileMode. create); if (FtpServerIP = null | FtpServerIP. trim (). length = 0) {throw new Exception (ftp download target server address is not set !);} Uri uri = new Uri (ftp: // + FtpServerIP +/+ remoteFileName); ftpsize = (FtpWebRequest) FtpWebRequest. create (uri); ftpsize. useBinary = true; reqFTP = (FtpWebRequest) FtpWebRequest. create (uri); reqFTP. useBinary = true; if (ifCredential) // use user identity authentication {ftpsize. credentials = new NetworkCredential (FtpUserID, FtpPassword); reqFTP. credentials = new NetworkCredential (FtpUserID, FtpPassword);} ftpsize. metho D = WebRequestMethods. ftp. getFileSize; FtpWebResponse re = (FtpWebResponse) ftpsize. getResponse (); long totalBytes = re. contentLength; re. close (); reqFTP. method = WebRequestMethods. ftp. downloadFile; response = (FtpWebResponse) reqFTP. getResponse (); ftpStream = response. getResponseStream (); // update progress if (updateProgress! = Null) {updateProgress (int) totalBytes, 0); // update progress bar} long totalDownloadedByte = 0; int bufferSize = 2048; int readCount; byte [] buffer = new byte [bufferSize]; readCount = ftpStream. read (buffer, 0, bufferSize); while (readCount> 0) {totalDownloadedByte = readCount + totalDownloadedByte; outputStream. write (buffer, 0, readCount); // update progress if (updateProgress! = Null) {updateProgress (int) totalBytes, (int) totalDownloadedByte); // update progress bar} readCount = ftpStream. read (buffer, 0, bufferSize);} ftpStream. close (); outputStream. close (); response. close (); return true;} catch (Exception) {return false; throw;} finally {if (ftpStream! = Null) {ftpStream. Close ();} if (outputStream! = Null) {outputStream. Close ();} if (response! = Null) {response. Close () ;}}# endregion # region upload the file to the FTP server ///
  /// Upload the file to the FTP server //////
  Local file name with full path ///
  Report Progress processing (first parameter: total size, second parameter: current progress )///
  
   
Download successful?
  Public static bool FtpUploadFile (string localFullPath, Action
  
   
UpdateProgress = null) {FtpWebRequest reqFTP; Stream stream = null; FtpWebResponse response = null; FileStream fs = null; try {FileInfo finfo = new FileInfo (localFullPath ); if (FtpServerIP = null | FtpServerIP. trim (). length = 0) {throw new Exception (the address of the target ftp upload server is not set !);} Uri uri = new Uri (ftp: // + FtpServerIP +/+ finfo. name); reqFTP = (FtpWebRequest) FtpWebRequest. create (uri); reqFTP. keepAlive = false; reqFTP. useBinary = true; reqFTP. credentials = new NetworkCredential (FtpUserID, FtpPassword); // user, password reqFTP. method = WebRequestMethods. ftp. uploadFile; // send the download Request command reqFTP to the server. contentLength = finfo. length; // specify the size of the uploaded file for the request. response = reqFTP. getResponse () as FtpWebRe Restore se; reqFTP. contentLength = finfo. length; int buffLength = 1024; byte [] buff = new byte [buffLength]; int contentLen; fs = finfo. openRead (); stream = reqFTP. getRequestStream (); contentLen = fs. read (buff, 0, buffLength); int allbye = (int) finfo. length; // update progress if (updateProgress! = Null) {updateProgress (int) allbye, 0); // update progress bar} int startbye = 0; while (contentLen! = 0) {startbye = contentLen + startbye; stream. Write (buff, 0, contentLen); // update progress if (updateProgress! = Null) {updateProgress (int) allbye, (int) startbye); // update progress bar} contentLen = fs. read (buff, 0, buffLength);} stream. close (); fs. close (); response. close (); return true;} catch (Exception) {return false; throw;} finally {if (fs! = Null) {fs. Close ();} if (stream! = Null) {stream. Close () ;}if (response! = Null) {response. Close () ;}}# endregion }}
  
 

 

Call instance:

Download (path without iis ):

 

FileUpDownload. FtpServerIP = 192.168.1.1; FileUpDownload. FtpUserID = ftpTest001; FileUpDownload. FtpPassword = aaaaaa; FileUpDownload. FtpDownload (Beyond downloads, Application. StartupPath +/downloads, false );

 

Previously uploaded file directory:

Upload (path without iis ):

 

OpenFileDialog op = new OpenFileDialog (); op. initialDirectory = Application. startupPath; op. restoreDirectory = true; op. filter = compressed file (*. zip) | *. zip | compressed file (*. rar) | *. rar | all files (*. *) | *. *; if (op. showDialog () = DialogResult. OK) {string aa = op. fileName; FileUpDownload. ftpServerIP = 192.168.1.1; FileUpDownload. ftpUserID = ftpTest001; FileUpDownload. ftpPassword = aaaaaa; // full path FileUpDownload. ftpUploadFile (aa );}

 

 

 



 

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.