C # winfrom Analog FTP file Management implementation code

Source: Internet
Author: User
Tags ftp file
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 FTP {//Create FtpWebRequest object based on URI reqftp = (ftpwebrequest)            Ftpwebrequest.create (The new Uri (path));            Specifies the data transfer type reqftp.usebinary = TRUE;        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;            }//Both call this private string[] getfilelist (string path, string wrmethods)//The above code example how to get 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 above code example how to get the file list {return getfilelis from the FTP server        T ("ftp://" + Ftpserverip + "/" + path, WebRequestMethods.Ftp.ListDirectory); } public string[] Getfilelist ()//The above code example how to get the file list {return getfilelist ("ftp://" + ftpser) from the FTP server        Verip + "/", WebRequestMethods.Ftp.ListDirectory); The public void Upload (string filename)//code above implements the ability to upload files from an FTP server {FileInfo fileinf = new FileInfo (            filename);            String uri = "ftp://" + Ftpserverip + "/" + fileinf.name;            Connect (URI);//connect//default is True, the connection will not be closed//After a command is executed reqftp.keepalive = false;            Specifies what command to execute Reqftp.method = WebRequestMethods.Ftp.UploadFile;            Notifies server file size when uploading a file Reqftp.contentlength = Fileinf.length;            Buffer size set 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 ();                try {//writes the uploaded file to stream stream strm = Reqftp.getrequeststream (); KB Contentlen per read file stream = fs.                Read (Buff, 0, bufflength);                      Stream content does not end while (Contentlen! = 0) {//writes content from file stream to upload stream Strm.                    Write (Buff, 0, Contentlen); Contentlen = fs.                Read (Buff, 0, bufflength); }//Close two stream 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 ability to download files from an FTP server {try {StringOnlyfilename = Path.getfilename (fileName);                String newfilename = FilePath + "\ \" + Onlyfilename; if (file.exists (NewFileName)) {errorinfo = string.                    Format ("Local file {0} already exists, could not be downloaded", newfilename);                return false;                } string url = "ftp://" + Ftpserverip + "/" + fileName;                Connect (URL);//Connect 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 ("cannot download because {0}", ex.)                Message);            return false;                 }}//delete file public void Deletefilename (string fileName) {try {                 FileInfo Fileinf = new FileInfo (fileName);                 String uri = "ftp://" + Ftpserverip + "/" + fileinf.name; Connect (URI);//connect//default is True, the connection is not closed//executed after a command Reqftp.keepali                 ve = false;                 Specifies what 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 directory public void MakeDir (string dirName) {try {s                Tring uri = "ftp://" + Ftpserverip + "/" + dirName;                Connect (URI);//Connection Reqftp.method = WebRequestMethods.Ftp.MakeDirectory;                FtpWebResponse response = (ftpwebresponse) reqftp.getresponse (); Response.            Close (); } catch (Exception ex) {MessageBox.Show (ex.            Message); }}//delete directory public void Deldir (string dirName) {try {s                Tring uri = "ftp://" + Ftpserverip + "/" + dirName; Connect (URI);//Connection Reqftp.method = WebRequestMethods.Ftp.ReMoveDirectory;                FtpWebResponse response = (ftpwebresponse) reqftp.getresponse (); Response.            Close (); } catch (Exception ex) {MessageBox.Show (ex.            Message);            }}//Get file size public long getfilesize (string filename) {long fileSize = 0;                try {FileInfo fileinf = new FileInfo (filename);                String uri = "ftp://" + Ftpserverip + "/" + fileinf.name;                Connect (URI);//Connection Reqftp.method = WebRequestMethods.Ftp.GetFileSize;                FtpWebResponse response = (ftpwebresponse) reqftp.getresponse (); FileSize = Response.                ContentLength; Response.            Close (); } catch (Exception ex) {MessageBox.Show (ex.            Message);        } return fileSize; }//file renamed public void Rename (string currentfilename, STring NewFileName) {try {FileInfo fileinf = new FileInfo (currentfilename);                String uri = "ftp://" + Ftpserverip + "/" + fileinf.name;                Connect (URI);//Connection 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 file Clear public string[] Getfilesdetaillist () {return getfilelist ("ftp://" +        Ftpserverip + "/", WebRequestMethods.Ftp.ListDirectoryDetails); }//Get file Clear public string[] Getfilesdetaillist (string path) {return getfilelist ("ftp:/ /"+ Ftpserverip +"/" + path, WebRequestMethods.Ftp.ListDirectoryDetails); }    }}

Above is a class, for example to prove 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", "John Doe"); } 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 "," 123456 "); Ftpupdown.makedir (this. Txt_name.        Text);            }//Get FTP file Clear file, also for processing, be able to get all the file name 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.