C winfrom emulates the ftp file management implementation code

  • 2020-06-03 08:10:30
  • OfStack


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)// The connection ftp
        {
            //  According to the uri create FtpWebRequest object 
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));
            //  Specifies the data transfer type 
            reqFTP.UseBinary = true;
            // ftp Username 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;
        }

        // I'm gonna call this 
        private string[] GetFileList(string path, string WRMethods)// The above code example shows how to get from ftp Get a list of files on the 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 shows how to get from ftp Get a list of files on the server 
        {
            return GetFileList("ftp://" + ftpServerIP + "/" + path, WebRequestMethods.Ftp.ListDirectory);

        }

 

        public string[] GetFileList()// The above code example shows how to get from ftp Get a list of files on the server 
        {
            return GetFileList("ftp://" + ftpServerIP + "/", WebRequestMethods.Ftp.ListDirectory);
        }

        public void Upload(string filename) // The above code implements the following ftp The ability for the server to upload files 
        {
            FileInfo fileInf = new FileInfo(filename);
            string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
            Connect(uri);// The connection        
            //  The default is true , the connection will not be closed  
            //  in 1 The command is then executed  
            reqFTP.KeepAlive = false;
            //  What commands do you specify to execute  
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
            //  Notify the server of the file size when the file is uploaded  
            reqFTP.ContentLength = fileInf.Length;
            //  Buffer size is set to kb  
            int buffLength = 2048;

            byte[] buff = new byte[buffLength];
            int contentLen;
            //  Open the 1 A file stream (System.IO.FileStream)  Read the uploaded file  
            FileStream fs = fileInf.OpenRead();
            try
            {
                //  Write the uploaded file to the stream  
                Stream strm = reqFTP.GetRequestStream();
                //  Every time a file stream is read kb  
                contentLen = fs.Read(buff, 0, buffLength);
                //  The stream content does not end  
                while (contentLen != 0)
                {
                    //  The content from file stream  write upload stream  
                    strm.Write(buff, 0, contentLen);
                    contentLen = fs.Read(buff, 0, buffLength);
                }
                //  Close both 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 following ftp The ability for the server to download files 
        {
            try
            {
                String onlyFileName = Path.GetFileName(fileName);
                string newFileName = filePath + "\\" + onlyFileName;
                if (File.Exists(newFileName))
                {
                    errorinfo = string.Format(" The local file {0} existing , Unable to download ", newFileName);
                    return false;
                }
                string url = "ftp://" + ftpServerIP + "/" + fileName;
                Connect(url);// The connection    
                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(" Due to the {0}, Unable to download ", ex.Message);
                return false;
            }
        }

        // Delete the file 

         public void DeleteFileName(string fileName)
         {
             try
             {
                 FileInfo fileInf = new FileInfo(fileName);
                 string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
                 Connect(uri);// The connection          
                 //  The default is true , the connection will not be closed 

                 //  in 1 The command is then executed 

                 reqFTP.KeepAlive = false;

                 //  What commands do you specify to execute 

                 reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
                 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                 response.Close();
             }
             catch (Exception ex)
             {
                 MessageBox.Show(ex.Message, " Delete the error ");
             }
         }

        // Create a directory 

        public void MakeDir(string dirName)
        {
            try
            {
                string uri = "ftp://" + ftpServerIP + "/" + dirName;
                Connect(uri);// The connection         
                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);// The 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);// The 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;
        }

        // The file name  
        public void Rename(string currentFilename, string newFilename)
        {
            try
            {
                FileInfo fileInf = new FileInfo(currentFilename);
                string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
                Connect(uri);// The 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);
            }
        }

        // Obtain document clarity  
        public string[] GetFilesDetailList()
        {
            return GetFileList("ftp://" + ftpServerIP + "/", WebRequestMethods.Ftp.ListDirectoryDetails);
        } 
        // Obtain document clarity  
        public string[] GetFilesDetailList(string path) 
        { 
            return GetFileList("ftp://" + ftpServerIP + "/" + path, WebRequestMethods.Ftp.ListDirectoryDetails); 
        }

    }
}

The above is a class. 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 the 
        {
            FtpUpDown ftpUpDown = new FtpUpDown("192.168.2.130:21", "wl", "123456");
            ftpUpDown.Rename(" zhang 3", " li 4");
        }
 private void button4_Click(object sender, EventArgs e)// delete 
        {
            FtpUpDown ftpUpDown = new FtpUpDown("192.168.2.130:21", "wl", "123456");
            ftpUpDown.delDir(" zhang 3");
        }
 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);
        }

 
// To obtain ftp The file of the file is clear, and for processing, all file names can be obtained 
 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 articles: