Ftp实习文件上传,下载单个件及文件夹下面所有文件,获取文件列表功能

窗体设计

#region Windows 窗体设计器生成的代码

        /// <summary>
        /// 设计器支持所需的方法 - 不要
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmList));
            this.btnDown = new System.Windows.Forms.Button();
            this.btnGetList = new System.Windows.Forms.Button();
            this.treeView1 = new System.Windows.Forms.TreeView();
            this.imageList1 = new System.Windows.Forms.ImageList(this.components);
            this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components);
            this.下载浏览ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.webBrowser1 = new System.Windows.Forms.WebBrowser();
            this.文件上传ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.contextMenuStrip1.SuspendLayout();
            this.SuspendLayout();
            // 
            // btnDown
            // 
            this.btnDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
            this.btnDown.Location = new System.Drawing.Point(14, 597);
            this.btnDown.Name = "btnDown";
            this.btnDown.Size = new System.Drawing.Size(75, 23);
            this.btnDown.TabIndex = 0;
            this.btnDown.Text = "下载文件";
            this.btnDown.UseVisualStyleBackColor = true;
            // 
            // btnGetList
            // 
            this.btnGetList.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
            this.btnGetList.Location = new System.Drawing.Point(95, 597);
            this.btnGetList.Name = "btnGetList";
            this.btnGetList.Size = new System.Drawing.Size(75, 23);
            this.btnGetList.TabIndex = 0;
            this.btnGetList.Text = "获取文件列表";
            this.btnGetList.UseVisualStyleBackColor = true;
            this.btnGetList.Click += new System.EventHandler(this.btnGetList_Click);
            // 
            // treeView1
            // 
            this.treeView1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        | System.Windows.Forms.AnchorStyles.Left)));
            this.treeView1.ImageIndex = 0;
            this.treeView1.ImageList = this.imageList1;
            this.treeView1.Location = new System.Drawing.Point(12, 12);
            this.treeView1.Name = "treeView1";
            this.treeView1.SelectedImageIndex = 0;
            this.treeView1.Size = new System.Drawing.Size(207, 579);
            this.treeView1.TabIndex = 1;
            this.treeView1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.treeView1_MouseDown);
            // 
            // imageList1
            // 
            this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream")));
            this.imageList1.TransparentColor = System.Drawing.Color.Transparent;
            this.imageList1.Images.SetKeyName(0, "folderopen.ico");
            // 
            // contextMenuStrip1
            // 
            this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.下载浏览ToolStripMenuItem,
            this.文件上传ToolStripMenuItem});
            this.contextMenuStrip1.Name = "contextMenuStrip1";
            this.contextMenuStrip1.RenderMode = System.Windows.Forms.ToolStripRenderMode.System;
            this.contextMenuStrip1.Size = new System.Drawing.Size(153, 70);
            // 
            // 下载浏览ToolStripMenuItem
            // 
            this.下载浏览ToolStripMenuItem.Name = "下载浏览ToolStripMenuItem";
            this.下载浏览ToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
            this.下载浏览ToolStripMenuItem.Text = "下载浏览";
            this.下载浏览ToolStripMenuItem.Click += new System.EventHandler(this.下载浏览ToolStripMenuItem_Click);
            // 
            // webBrowser1
            // 
            this.webBrowser1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.webBrowser1.Location = new System.Drawing.Point(241, 12);
            this.webBrowser1.MinimumSize = new System.Drawing.Size(20, 20);
            this.webBrowser1.Name = "webBrowser1";
            this.webBrowser1.Size = new System.Drawing.Size(553, 579);
            this.webBrowser1.TabIndex = 3;
            // 
            // 文件上传ToolStripMenuItem
            // 
            this.文件上传ToolStripMenuItem.Name = "文件上传ToolStripMenuItem";
            this.文件上传ToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
            this.文件上传ToolStripMenuItem.Text = "文件上传";
            this.文件上传ToolStripMenuItem.Click += new System.EventHandler(this.文件上传ToolStripMenuItem_Click);
            // 
            // frmList
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(806, 632);
            this.Controls.Add(this.treeView1);
            this.Controls.Add(this.webBrowser1);
            this.Controls.Add(this.btnGetList);
            this.Controls.Add(this.btnDown);
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.Name = "frmList";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "公告下载浏览";
            this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
            this.Load += new System.EventHandler(this.Form1_Load);
            this.contextMenuStrip1.ResumeLayout(false);
            this.ResumeLayout(false);

        }

        #endregion


FTP通用操作类

  class FtpDownLoad
    {
        private string password;
        public string Password
        {
           get { return password; }
           set { password = value; }
        }
        private string userName;
        public string UserName
       {
          get { return userName; }
          set { userName = value; }
       }
        private string ftpServerIP;
        public string FtpServerIP
       {
          get { return ftpServerIP; }
          set { ftpServerIP = value; }
       }

        public FtpDownLoad( string userName,string password)
        {
            this.password = password;
            this.userName=userName;
        }
        #region ---------连接ftp ConnFtp(string ftpServerIP)
        /// <summary>
        /// 连接ftp
        /// </summary>
        public void ConnFtp(string ftpServerIP)
        {
            try
            {
                FtpWebRequest ftpRequest = null;
                ftpRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpServerIP));//创建实现文件传输协议ftp客户端
                ftpRequest.UseBinary = true;//指定文件传输类型
                ftpRequest.Credentials = new NetworkCredential(userName, password);//获取设置与ftp服务器通信凭证
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        } 
        #endregion

        #region ---------获取文件详细目录 string[] GetDetailList(string ftpServerIP)
        /// <summary>
        /// 获取文件详细目录
        /// </summary>
        /// ftppath ftp上文件路径 如:ftp://192.168.1.1//wangqihe
        /// <returns></returns>
        public string[] GetDetailList(string ftppath)
        {
            try
            {
                StringBuilder list = new StringBuilder();//存放文件名,大小 等信息
                FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftppath));//创建实现文件传输协议ftp客户端
                request.Credentials = new NetworkCredential(userName, password);//获取设置与ftp服务器通信凭证
                request.KeepAlive = false;
                request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;//表示获取ftp文件详细信息
                WebResponse reponse = request.GetResponse();
                long filelength = reponse.ContentLength;//获取文件长度
                StreamReader reader = new StreamReader(reponse.GetResponseStream(), System.Text.Encoding.Default);
                string line = reader.ReadLine();
                while (line != null)
                {
                    list.Append(line);
                    list.Append("龘");//用不常用字方便进行分割
                    line = reader.ReadLine();
                }
                reader.Close();
                reponse.Close();
                return list.ToString().Split('龘');
            }
            catch (Exception ex)
            {
                return null;
                throw;
            }
        } 
        #endregion

        #region ---------只获取ftp文件 string[] GetDirectoryList(string path)
        /// <summary>
        /// 只获取ftp文件
        /// </summary>
        /// <returns></returns>
        public string[] GetDirectoryList(string path)
        {
            string[] list = GetDetailList(path);
            string m = "";
            for (int i = 0; i < list.Length - 1; i++)
            {
                int dirPos = list[i].IndexOf("<DIR>");
                if (dirPos > 0)
                {
                    /*判断 Windows 风格*/
                    m += list[i].Substring(dirPos + 5).Trim() + "\n";
                }
                else if (list[i].Trim().Substring(0, 1).ToUpper() == "D")
                {
                    /*判断 Unix 风格*/
                    string dir = list[i].Substring(54).Trim();
                    if (dir != "." && dir != "..")
                    {
                        m += dir + "\n";
                    }
                }
            }
            return m.Split('\n');
        } 
        #endregion

        #region ---------判断文件是否为文件夹 bool IsFolder(string strName)
        public bool IsFolder(string strName)
        {
            string m = string.Empty;
            int dirPos = strName.IndexOf("<DIR>");
            if (dirPos > 0)
            {
                /*判断 Windows 风格*/
                m += strName.Substring(dirPos + 5).Trim() + "\n";
                return true;
            }
            else if (strName.Trim().Substring(0, 1).ToUpper() == "D")
            {
                /*判断 Unix 风格*/
                string dir = strName.Substring(54).Trim();
                if (dir != "." && dir != "..")
                {
                    m += dir + "\n";
                    return true;
                }
            }
            return false;
        } 
        #endregion

        #region ---------单个文件下载方法 void download(string adss, string ftpadss)
        /// <summary>
        /// 单个文件下载方法
        /// </summary>
        /// <param name="adss">保存文件的本地路径</param>
        /// <param name="ftpadss">下载文件的FTP路径</param>
        public void download(string adss, string ftpadss)
        {
            try
            {
                //FileMode常数确定如何打开或创建文件,指定操作系统应创建新文件。
                //FileMode.Create如果文件已存在,它将被改写
                FileStream outputStream = new FileStream(adss, FileMode.Create);
                FtpWebRequest downRequest = (FtpWebRequest)WebRequest.Create(new Uri(ftpadss));
                //设置要发送到 FTP 服务器的命令
                downRequest.Credentials = new NetworkCredential(userName, password);
                downRequest.Method = WebRequestMethods.Ftp.DownloadFile;
                FtpWebResponse response = (FtpWebResponse)downRequest.GetResponse();
                Stream ftpStream = response.GetResponseStream();
                long cl = response.ContentLength;//ftp上获取文件的长度
                int bufferSize = 2048;//一次获取文件大小 为 2M
                int readCount;
                byte[] buffer = new byte[bufferSize];//设置缓存区
                readCount = ftpStream.Read(buffer, 0, bufferSize);//从当前流中读取字节到缓存 buffer中  readCount读取字节数
                while (readCount > 0)//读取字节数大于O循环读取
                {
                    outputStream.Write(buffer, 0, readCount);//从缓存区读取字节到流中
                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                }
                ftpStream.Close();
                outputStream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        } 
        #endregion
        /// </summary>
        /// <param name="ftpads">FTP地址路径</param>
        /// <param name="name">我们所选择的文件或者文件夹名字</param>
        /// <param name="type">要发送到FTP服务器的命令</param>
        /// <returns></returns>
        public string[] ftp(string ftpads, string name, string type)
        {
            WebResponse webresp = null;
            StreamReader ftpFileListReader = null;
            FtpWebRequest ftpRequest = null;
            try
            {
                ftpRequest = (FtpWebRequest)WebRequest.Create(new Uri(ftpads + name));
                ftpRequest.UseBinary = true;
                ftpRequest.Credentials = new NetworkCredential("wangqihe", "123456");
                ftpRequest.Method = type;
                webresp = ftpRequest.GetResponse();
                ftpFileListReader = new StreamReader(webresp.GetResponseStream(), Encoding.Default);
            }
            catch (Exception ex)
            {
                ex.ToString();
            }
            StringBuilder str = new StringBuilder();
            string line = ftpFileListReader.ReadLine();
            while (line != null)
            {
                str.Append(line);
                str.Append("鼯");
                line = ftpFileListReader.ReadLine();
            }
            string[] fen = str.ToString().Split('鼯');
            return fen;
        }

        #region ---------下载文件下的所有文件 void downftp(string ftpads, string name, string Myads)
        /// <summary>
        /// 下载方法KO
        /// </summary>
        /// <param name="ftpads">FTP路径</param>
        /// <param name="name">需要下载文件路径</param>
        /// <param name="Myads">保存的本地路径</param>
        public void downftp(string ftpads, string name, string Myads)
        {
            string downloadDir = Myads + name;
            string ftpdir = ftpads + name;
            string[] fullname = ftp(ftpads, name, WebRequestMethods.Ftp.ListDirectoryDetails);
            //判断是否为单个文件 
            if (fullname.Length <= 2)
            {
                if (fullname[fullname.Length - 1] == "")
                {
                    download(downloadDir + "/" + name, ftpads + name + "/" + name);
                }
            }
            else
            {
                string[] onlyname = ftp(ftpads, name, WebRequestMethods.Ftp.ListDirectory);
                if (!Directory.Exists(downloadDir))
                {
                    Directory.CreateDirectory(downloadDir);
                }
                foreach (string names in fullname)
                {
                    //判断是否具有文件夹标识<DIR>
                    if (names.StartsWith("d") && (!names.EndsWith(".")))
                    {
                        string olname = names.Substring(names.IndexOf(':') + 3).TrimStart();
                        //string olname = names.Split(new string[] { "<DIR>" }, 
                        //StringSplitOptions.None)[1].Trim();
                        downftp(ftpdir, "//" + olname, downloadDir);
                    }
                    else
                    {
                        foreach (string onlynames in onlyname)
                        {
                            if (onlynames == "" || onlynames == " " || names == "")
                            {
                                break;
                            }
                            else
                            {
                                if (names.Contains(" " + onlynames))
                                {
                                    download(downloadDir + "/" + onlynames, ftpads + name + "/" +
                                    onlynames);
                                    break;
                                }
                            }
                        }
                    }
                }
            }

        } 
        #endregion


        #region ftp服务器上载文件的功能 string Upload(string data, string filename, string file)
        //ftp服务器上载文件的功能
        public string Upload(string data, string filename, string file)
        {
            FileInfo fileInf = new FileInfo(filename);
            string uri = file + "\\" + data;
            FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
            reqFTP.Credentials = new NetworkCredential("wangqihe", "123456");//获取设置与ftp服务器通信凭证
            // 默认为true,连接不会被关闭  yyyyMMddHHmmss
            // 在一个命令之后被执行
            reqFTP.KeepAlive = false;
            // 指定执行什么命令
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
            // 上传文件时通知服务器文件的大小
            reqFTP.ContentLength = fileInf.Length;
            // 缓冲大小设置为kb
            int buffLength = 2048;
            byte[] buff = new byte[buffLength];
            int contentLen;
            // 打开一个文件流(System.IO.FileStream) 去读上传的文件
            FileStream fs = fileInf.OpenRead();
            try
            {
                // 把上传的文件写入流
                Stream strm = reqFTP.GetRequestStream();
                // 每次读文件流的kb
                contentLen = fs.Read(buff, 0, buffLength);
                int totalDownloadedByte = 0;
                // 流内容没有结束
                while (contentLen != 0)
                {
                    totalDownloadedByte = contentLen + totalDownloadedByte; //更新文件
                    // 把内容从file stream 写入upload stream
                    strm.Write(buff, 0, contentLen);

                    contentLen = fs.Read(buff, 0, buffLength);
                }
                // 关闭两个流
                strm.Close();
                fs.Close();
                return "";
            }
            catch (Exception ex)
            {
                return "Upload Error" + ex.Message;
            }
        } 
        #endregion

        public static void DeleteFileName(string fileName)
        {
            try
            {
                string uri = fileName;
                FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                // 默认为true,连接不会被关闭
                // 在一个命令之后被执行
                reqFTP.KeepAlive = false;
                // 指定执行什么命令
                reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                response.Close();
            }
            catch (Exception ex)
            {

            }
        }

        public static string MakeDir(string dirName)
        {
            try
            {
                string uri = dirName;
                FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                response.Close();
                return "";
            }
            catch (WebException ex)
            {
                return "[Make Dir]" + ex.Message;
            }
        }
        //获得文件大小
        public long GetFileSize(string filename)
        {
            long fileSize = 0;
            try
            {
                FileInfo fileInf = new FileInfo(filename);
                string uri =  fileInf.Name;
                FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                fileSize = response.ContentLength;
                response.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return fileSize;
        }
    }


事件

 public frmList()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void btnGetList_Click(object sender, EventArgs e)
        {

            Bind();
        }
        #region ----------获取ftp文件列表 void Bind()
        private void Bind()
        {
            TreeNode root = null;
            treeView1.Nodes.Clear();
            try
            {
                FtpDownLoad ftp = new FtpDownLoad("wangqihe", "123456");
                string[] ss = ftp.GetDirectoryList("ftp://192.168.1.20/notice");
                
                for (int i = 0; i < ss.Length - 1; i++)
                {
                    root = treeView1.Nodes.Add(ss[i].ToString());
                    FillTree_Detail(root, ss[i].ToString());
                }
                root.Expand();

                this.treeView1.SelectedNode = root;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示!ʾ", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void FillTree_Detail(TreeNode root,string dd)
        {
            TreeNode item = null;
            FtpDownLoad ftp = new FtpDownLoad("wangqihe", "123456");
            string[] s2 = ftp.GetDetailList("ftp://192.168.1.20/notice/" + dd.Trim());

            for (int i = 3; i < s2.Length - 1; i++)
            {
                item = root.Nodes.Add(s2[i].ToString().Substring(54));
                if (ftp.IsFolder(s2[i].ToString()))
                {
                    FillTree_Detail(item, dd +"/"+ s2[i].ToString().Substring(54).Trim());
                }
            }
        }
        #endregion

        private void treeView1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)//判断你点的是不是右键
            {
                Point ClickPoint = new Point(e.X, e.Y);
                TreeNode CurrentNode = treeView1.GetNodeAt(ClickPoint);
                if (CurrentNode != null)//判断你点的是不是一个节点
                {
                    CurrentNode.ContextMenuStrip = contextMenuStrip1;
                    treeView1.SelectedNode = CurrentNode;//选中这个节点
                }
            }
        }

        private void 下载浏览ToolStripMenuItem_Click(object sender, EventArgs e)
        {
              FtpDownLoad ftp = new FtpDownLoad("wangqihe", "123456");
              ftp.downftp("ftp://192.168.1.20/notice/", treeView1.SelectedNode.Text, "f://");
              if (ftp.IsFolder(treeView1.SelectedNode.Text))
              {
                  webBrowser1.Url = new Uri("f:/" + treeView1.SelectedNode.Text + "/default.html");
              }
              else
              {
                  webBrowser1.Url = new Uri("f:/" + treeView1.SelectedNode.Text);
              }
        }

        private void 文件上传ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FtpDownLoad ftp = new FtpDownLoad("wangqihe", "123456");
            ftp.Upload(DateTime.Now.ToString("yyyyMMddhhmmss"), "f://222.html", "ftp://192.168.1.20/notice/" + treeView1.SelectedNode.Text);
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值