C # winfrom implements analog ftp file management,

Source: Internet
Author: User
Tags ftp file

C # winfrom implements analog ftp file management,

Using System; using System. collections. generic; using System. text; using System. net; using System. IO; using System. windows. forms; namespace ConvertData {class FtpUpDown {string ftpServerIP; string ftpUserID; string ftpPassword; FtpWebRequest reqFTP; private void Connect (String path) // connect to ftp {// create FtpWebRequest object reqFTP = (FtpWebRequest) FtpWebRequest according to uri. create (new Uri (path); // specify the data transmission type reqFTP. useBin Ary = true; // The ftp user name and password reqFTP. credentials = new NetworkCredential (ftpUserID, ftpPassword);} public FtpUpDown (string ftpServerIP, string ftpUserID, string ftpPassword) {this. ftpServerIP = ftpServerIP; this. ftpUserID = ftpUserID; this. ftpPassword = ftpPassword;} // call this private string [] GetFileList (string path, string WRMethods) // The code above demonstrates how to obtain the file list from the ftp server {string [] downloadFiles; StringBuilder Result = new StringBuilder (); try {Connect (path); reqFTP. method = WRMethods; WebResponse response = reqFTP. getResponse (); StreamReader reader = new StreamReader (response. getResponseStream (), System. text. encoding. default); // Chinese file name string line = reader. readLine (); while (line! = Null) {result. append (line); result. append ("\ n"); line = reader. readLine ();} // to remove the trailing '\ n' result. remove (result. toString (). lastIndexOf ('\ n'), 1); reader. close (); response. close (); return result. toString (). split ('\ n');} catch (Exception ex) {System. windows. forms. messageBox. show (ex. message); downloadFiles = null; return downloadFiles;} public string [] GetFileList (string path) // The code above demonstrates how to obtain the file list from the ftp server {return GetFileList ("ftp: //" + ftpServerIP + "/" + path, WebRequestMethods. ftp. listDirectory);} public string [] GetFileList () // The code above demonstrates how to obtain the file list from the ftp server {return GetFileList ("ftp: // "+ ftpServerIP +"/", WebRequestMethods. ftp. listDirectory);} public void Upload (string filename) // the above Code implements the function of uploading files from the ftp server {FileInfo fileInf = new FileInfo (filename ); string uri = "ftp ://" + FtpServerIP + "/" + fileInf. name; Connect (uri); // connection // The default value is true, and the connection will not be closed // reqFTP is executed after a command. keepAlive = false; // specifies the command to execute reqFTP. method = WebRequestMethods. ftp. uploadFile; // notify the server of the file size reqFTP when uploading the file. contentLength = fileInf. length; // set the buffer size to kb int buffLength = 2048; byte [] buff = new byte [buffLength]; int contentLen; // open a file stream (System. IO. fileStream) to read the uploaded file FileStream fs = fileInf. openRead (); tr Y {// write the uploaded file to the Stream strm = reqFTP. getRequestStream (); // kb contentLen = fs. read (buff, 0, buffLength); // The stream content has not ended while (contentLen! = 0) {// write content from file stream to upload stream strm. write (buff, 0, contentLen); contentLen = fs. read (buff, 0, buffLength);} // close two streams strm. close (); fs. close ();} catch (Exception ex) {MessageBox. show (ex. message, "Upload Error") ;}} public bool Download (string filePath, string fileName, out string errorinfo) /// the above Code implements the file download function from the ftp server {try {String onlyFileName = Path. getFileName (fileName); string newFileName = filePath + "\" + onlyFileName; if (File. exists (newFileName) {errorinfo = string. format ("the local file {0} already exists and cannot be downloaded", newFileName); return false;} string url = "ftp: //" + ftpServerIP + "/" + fileName; connect (url); // Connect to reqFTP. credentials = new NetworkCredential (ftpUserID, ftpPassword); 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); FileStream outputStream = new FileStream (newFileName, FileMode. create); while (readCount> 0) {outputStream. write (buffer, 0, readCount); readCount = ftpStream. read (buffer, 0, bufferSize);} ftpStream. close (); outputStream. close (); response. close (); errorinfo = ""; return true;} catch (Exception ex) {errorinfo = string. format ("unable to download because {0}", ex. message); return false ;}}// Delete the public void DeleteFileName (string fileName) {try {FileInfo fileInf = new FileInfo (fileName); string uri = "ftp: // "+ ftpServerIP +"/"+ fileInf. name; Connect (uri); // connection // The default value is true, and the connection will not be closed // reqFTP is executed after a command. keepAlive = false; // specifies the command to execute reqFTP. method = WebRequestMethods. ftp. deleteFile; FtpWebResponse response = (FtpWebResponse) reqFTP. getResponse (); response. close ();} catch (Exception ex) {MessageBox. show (ex. message, "delete error") ;}}// create the public void MakeDir (string dirName) Directory {try {string uri = "ftp: // "+ ftpServerIP +"/"+ dirName; Connect (uri); // Connect to reqFTP. method = WebRequestMethods. ftp. makeDirectory; FtpWebResponse response = (FtpWebResponse) reqFTP. getResponse (); response. close ();} catch (Exception ex) {MessageBox. show (ex. message) ;}}// Delete the directory public void delDir (string dirName) {try {string uri = "ftp: //" + ftpServerIP + "/" + dirName; connect (uri); // Connect to reqFTP. method = WebRequestMethods. ftp. removeDirectory; FtpWebResponse response = (FtpWebResponse) reqFTP. getResponse (); response. close ();} catch (Exception ex) {MessageBox. show (ex. message) ;}}// get the file size public long GetFileSize (string filename) {long fileSize = 0; try {FileInfo fileInf = new FileInfo (filename); string uri = "ftp: // "+ ftpServerIP +"/"+ fileInf. name; Connect (uri); // Connect to reqFTP. method = WebRequestMethods. ftp. getFileSize; FtpWebResponse response = (FtpWebResponse) reqFTP. getResponse (); fileSize = response. contentLength; response. close ();} catch (Exception ex) {MessageBox. show (ex. message);} return fileSize;} // Rename the file public void Rename (string currentFilename, string newFilename) {try {FileInfo fileInf = new FileInfo (currentFilename); string uri = "ftp: // "+ ftpServerIP +"/"+ fileInf. name; Connect (uri); // Connect to reqFTP. method = WebRequestMethods. ftp. rename; reqFTP. renameTo = newFilename; FtpWebResponse response = (FtpWebResponse) reqFTP. getResponse (); // Stream ftpStream = response. getResponseStream (); // ftpStream. close (); response. close ();} catch (Exception ex) {MessageBox. show (ex. message) ;}}// get the object clear public string [] GetFilesDetailList () {return GetFileList ("ftp: //" + ftpServerIP + "/", WebRequestMethods. ftp. listDirectoryDetails);} // obtain the public string [] GetFilesDetailList (string path) {return GetFileList ("ftp: //" + ftpServerIP + "/" + path, WebRequestMethods. ftp. listDirectoryDetails );}}}

The above example shows how to substitute

Private void button1_Click (object sender, EventArgs e) // File Upload {FtpUpDown ftpUpDown = new FtpUpDown ("192.168.2.130: 21", "wl", "123456"); ftpUpDown. upload ("E: \ other.rar");} private void button3_Click (object sender, EventArgs e) // modify {FtpUpDown ftpUpDown = new FtpUpDown ("192.168.2.130: 21 ", "wl", "123456"); ftpUpDown. rename ("Zhang San", "Li Si");} private void button4_Click (object sender, EventArgs e) // Delete {FtpUpDown ftpUpDown = new FtpUpDown ("192.168.2.130: 21 ", "wl", "123456"); ftpUpDown. delDir ("Zhang San");} private void button2_Click (object sender, EventArgs e) // Add {FtpUpDown ftpUpDown = new FtpUpDown ("192.168.2.130: 21", "wl ", & quot; 123456 & quot;); ftpUpDown. makeDir (this. txT_name.Text);} // clear the ftp file. for processing, you can obtain all the file names FtpUpDown ftpUpDown = new FtpUpDown ("192.168.2.130", "wl ", "123456"); string [] str = ftpUpDown. getFilesDetailList (); int I = 1; foreach (string item in str) {string [] name = item. split (''); TxT_name.Text + = name [name. length-1] + ";"; I ++;} label1.Text = I. toString ();

  

  

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.