xuol001 发表于 2015-5-29 09:01:14

FTP文件上传下载,获取文件列表功能

  
  窗体设计器



1         #region Windows 窗体设计器生成的代码
2
3         ///
4         /// 设计器支持所需的方法 - 不要
5         /// 使用代码编辑器修改此方法的内容。
6         ///
7         private void InitializeComponent()
8         {
9             this.components = new System.ComponentModel.Container();
10             System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmList));
11             this.btnDown = new System.Windows.Forms.Button();
12             this.btnGetList = new System.Windows.Forms.Button();
13             this.treeView1 = new System.Windows.Forms.TreeView();
14             this.imageList1 = new System.Windows.Forms.ImageList(this.components);
15             this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components);
16             this.下载浏览ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
17             this.webBrowser1 = new System.Windows.Forms.WebBrowser();
18             this.文件上传ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
19             this.contextMenuStrip1.SuspendLayout();
20             this.SuspendLayout();
21             //
22             // btnDown
23             //
24             this.btnDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
25             this.btnDown.Location = new System.Drawing.Point(14, 597);
26             this.btnDown.Name = "btnDown";
27             this.btnDown.Size = new System.Drawing.Size(75, 23);
28             this.btnDown.TabIndex = 0;
29             this.btnDown.Text = "下载文件";
30             this.btnDown.UseVisualStyleBackColor = true;
31             //
32             // btnGetList
33             //
34             this.btnGetList.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
35             this.btnGetList.Location = new System.Drawing.Point(95, 597);
36             this.btnGetList.Name = "btnGetList";
37             this.btnGetList.Size = new System.Drawing.Size(75, 23);
38             this.btnGetList.TabIndex = 0;
39             this.btnGetList.Text = "获取文件列表";
40             this.btnGetList.UseVisualStyleBackColor = true;
41             this.btnGetList.Click += new System.EventHandler(this.btnGetList_Click);
42             //
43             // treeView1
44             //
45             this.treeView1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
46                         | System.Windows.Forms.AnchorStyles.Left)));
47             this.treeView1.ImageIndex = 0;
48             this.treeView1.ImageList = this.imageList1;
49             this.treeView1.Location = new System.Drawing.Point(12, 12);
50             this.treeView1.Name = "treeView1";
51             this.treeView1.SelectedImageIndex = 0;
52             this.treeView1.Size = new System.Drawing.Size(207, 579);
53             this.treeView1.TabIndex = 1;
54             this.treeView1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.treeView1_MouseDown);
55             //
56             // imageList1
57             //
58             this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream")));
59             this.imageList1.TransparentColor = System.Drawing.Color.Transparent;
60             this.imageList1.Images.SetKeyName(0, "folderopen.ico");
61             //
62             // contextMenuStrip1
63             //
64             this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
65             this.下载浏览ToolStripMenuItem,
66             this.文件上传ToolStripMenuItem});
67             this.contextMenuStrip1.Name = "contextMenuStrip1";
68             this.contextMenuStrip1.RenderMode = System.Windows.Forms.ToolStripRenderMode.System;
69             this.contextMenuStrip1.Size = new System.Drawing.Size(153, 70);
70             //
71             // 下载浏览ToolStripMenuItem
72             //
73             this.下载浏览ToolStripMenuItem.Name = "下载浏览ToolStripMenuItem";
74             this.下载浏览ToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
75             this.下载浏览ToolStripMenuItem.Text = "下载浏览";
76             this.下载浏览ToolStripMenuItem.Click += new System.EventHandler(this.下载浏览ToolStripMenuItem_Click);
77             //
78             // webBrowser1
79             //
80             this.webBrowser1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
81                         | System.Windows.Forms.AnchorStyles.Left)
82                         | System.Windows.Forms.AnchorStyles.Right)));
83             this.webBrowser1.Location = new System.Drawing.Point(241, 12);
84             this.webBrowser1.MinimumSize = new System.Drawing.Size(20, 20);
85             this.webBrowser1.Name = "webBrowser1";
86             this.webBrowser1.Size = new System.Drawing.Size(553, 579);
87             this.webBrowser1.TabIndex = 3;
88             //
89             // 文件上传ToolStripMenuItem
90             //
91             this.文件上传ToolStripMenuItem.Name = "文件上传ToolStripMenuItem";
92             this.文件上传ToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
93             this.文件上传ToolStripMenuItem.Text = "文件上传";
94             this.文件上传ToolStripMenuItem.Click += new System.EventHandler(this.文件上传ToolStripMenuItem_Click);
95             //
96             // frmList
97             //
98             this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
99             this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
100             this.ClientSize = new System.Drawing.Size(806, 632);
101             this.Controls.Add(this.treeView1);
102             this.Controls.Add(this.webBrowser1);
103             this.Controls.Add(this.btnGetList);
104             this.Controls.Add(this.btnDown);
105             this.MaximizeBox = false;
106             this.MinimizeBox = false;
107             this.Name = "frmList";
108             this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
109             this.Text = "公告下载浏览";
110             this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
111             this.Load += new System.EventHandler(this.Form1_Load);
112             this.contextMenuStrip1.ResumeLayout(false);
113             this.ResumeLayout(false);
114
115         }
116
117         #endregion
操作Ftp类


View Code


1 namespace FtpDown
2 {
3   class FtpDownLoad
4   {
5         private string password;
6         public string Password
7         {
8            get { return password; }
9            set { password = value; }
10         }
11         private string userName;
12         public string UserName
13      {
14         get { return userName; }
15         set { userName = value; }
16      }
17         private string ftpServerIP;
18         public string FtpServerIP
19      {
20         get { return ftpServerIP; }
21         set { ftpServerIP = value; }
22      }
23
24         public FtpDownLoad( string userName,string password)
25         {
26             this.password = password;
27             this.userName=userName;
28         }
29         #region ---------连接ftp ConnFtp(string ftpServerIP)
30         ///
31         /// 连接ftp
32         ///
33         public void ConnFtp(string ftpServerIP)
34         {
35             try
36             {
37               FtpWebRequest ftpRequest = null;
38               ftpRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpServerIP));//创建实现文件传输协议ftp客户端
39               ftpRequest.UseBinary = true;//指定文件传输类型
40               ftpRequest.Credentials = new NetworkCredential(userName, password);//获取设置与ftp服务器通信凭证
41             }
42             catch (Exception ex)
43             {
44               MessageBox.Show(ex.Message);
45             }
46         }
47         #endregion
48
49         #region ---------获取文件详细目录 string[] GetDetailList(string ftpServerIP)
50         ///
51         /// 获取文件详细目录
52         ///
53         /// ftppath ftp上文件路径 如:ftp://192.168.1.1//wangqihe
54         ///
55         public string[] GetDetailList(string ftppath)
56         {
57             try
58             {
59               StringBuilder list = new StringBuilder();//存放文件名,大小 等信息
60               FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftppath));//创建实现文件传输协议ftp客户端
61               request.Credentials = new NetworkCredential(userName, password);//获取设置与ftp服务器通信凭证
62               request.KeepAlive = false;
63               request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;//表示获取ftp文件详细信息
64               WebResponse reponse = request.GetResponse();
65               long filelength = reponse.ContentLength;//获取文件长度
66               StreamReader reader = new StreamReader(reponse.GetResponseStream(), System.Text.Encoding.Default);
67               string line = reader.ReadLine();
68               while (line != null)
69               {
70                     list.Append(line);
71                     list.Append("龘");//用不常用字方便进行分割
72                     line = reader.ReadLine();
73               }
74               reader.Close();
75               reponse.Close();
76               return list.ToString().Split('龘');
77             }
78             catch (Exception ex)
79             {
80               return null;
81               throw;
82             }
83         }
84         #endregion
85
86         #region ---------只获取ftp文件 string[] GetDirectoryList(string path)
87         ///
88         /// 只获取ftp文件
89         ///
90         ///
91         public string[] GetDirectoryList(string path)
92         {
93             string[] list = GetDetailList(path);
94             string m = "";
95             for (int i = 0; i < list.Length - 1; i++)
96             {
97               int dirPos = list.IndexOf("");
98               if (dirPos > 0)
99               {
100                     /*判断 Windows 风格*/
101                     m += list.Substring(dirPos + 5).Trim() + "\n";
102               }
103               else if (list.Trim().Substring(0, 1).ToUpper() == "D")
104               {
105                     /*判断 Unix 风格*/
106                     string dir = list.Substring(54).Trim();
107                     if (dir != "." && dir != "..")
108                     {
109                         m += dir + "\n";
110                     }
111               }
112             }
113             return m.Split('\n');
114         }
115         #endregion
116
117         #region ---------判断文件是否为文件夹 bool IsFolder(string strName)
118         public bool IsFolder(string strName)
119         {
120             string m = string.Empty;
121             int dirPos = strName.IndexOf("");
122             if (dirPos > 0)
123             {
124               /*判断 Windows 风格*/
125               m += strName.Substring(dirPos + 5).Trim() + "\n";
126               return true;
127             }
128             else if (strName.Trim().Substring(0, 1).ToUpper() == "D")
129             {
130               /*判断 Unix 风格*/
131               string dir = strName.Substring(54).Trim();
132               if (dir != "." && dir != "..")
133               {
134                     m += dir + "\n";
135                     return true;
136               }
137             }
138             return false;
139         }
140         #endregion
141
142         #region ---------单个文件下载方法 void download(string adss, string ftpadss)
143         ///
144         /// 单个文件下载方法
145         ///
146         /// 保存文件的本地路径
147         /// 下载文件的FTP路径
148         public void download(string adss, string ftpadss)
149         {
150             try
151             {
152               //FileMode常数确定如何打开或创建文件,指定操作系统应创建新文件。
153               //FileMode.Create如果文件已存在,它将被改写
154               FileStream outputStream = new FileStream(adss, FileMode.Create);
155               FtpWebRequest downRequest = (FtpWebRequest)WebRequest.Create(new Uri(ftpadss));
156               //设置要发送到 FTP 服务器的命令
157               downRequest.Credentials = new NetworkCredential(userName, password);
158               downRequest.Method = WebRequestMethods.Ftp.DownloadFile;
159               FtpWebResponse response = (FtpWebResponse)downRequest.GetResponse();
160               Stream ftpStream = response.GetResponseStream();
161               long cl = response.ContentLength;//ftp上获取文件的长度
162               int bufferSize = 2048;//一次获取文件大小 为 2M
163               int readCount;
164               byte[] buffer = new byte;//设置缓存区
165               readCount = ftpStream.Read(buffer, 0, bufferSize);//从当前流中读取字节到缓存 buffer中readCount读取字节数
166               while (readCount > 0)//读取字节数大于O循环读取
167               {
168                     outputStream.Write(buffer, 0, readCount);//从缓存区读取字节到流中
169                     readCount = ftpStream.Read(buffer, 0, bufferSize);
170               }
171               ftpStream.Close();
172               outputStream.Close();
173               response.Close();
174             }
175             catch (Exception ex)
176             {
177               MessageBox.Show(ex.Message);
178             }
179         }
180         #endregion
181         ///
182         /// FTP地址路径
183         /// 我们所选择的文件或者文件夹名字
184         /// 要发送到FTP服务器的命令
185         ///
186         public string[] ftp(string ftpads, string name, string type)
187         {
188             WebResponse webresp = null;
189             StreamReader ftpFileListReader = null;
190             FtpWebRequest ftpRequest = null;
191             try
192             {
193               ftpRequest = (FtpWebRequest)WebRequest.Create(new Uri(ftpads + name));
194               ftpRequest.UseBinary = true;
195               ftpRequest.Credentials = new NetworkCredential("wangqihe", "123456");
196               ftpRequest.Method = type;
197               webresp = ftpRequest.GetResponse();
198               ftpFileListReader = new StreamReader(webresp.GetResponseStream(), Encoding.Default);
199             }
200             catch (Exception ex)
201             {
202               ex.ToString();
203             }
204             StringBuilder str = new StringBuilder();
205             string line = ftpFileListReader.ReadLine();
206             while (line != null)
207             {
208               str.Append(line);
209               str.Append("鼯");
210               line = ftpFileListReader.ReadLine();
211             }
212             string[] fen = str.ToString().Split('鼯');
213             return fen;
214         }
215
216         #region ---------下载文件下的所有文件 void downftp(string ftpads, string name, string Myads)
217         ///
218         /// 下载方法KO
219         ///
220         /// FTP路径
221         /// 需要下载文件路径
222         /// 保存的本地路径
223         public void downftp(string ftpads, string name, string Myads)
224         {
225             string downloadDir = Myads + name;
226             string ftpdir = ftpads + name;
227             string[] fullname = ftp(ftpads, name, WebRequestMethods.Ftp.ListDirectoryDetails);
228             //判断是否为单个文件
229             if (fullname.Length
页: [1]
查看完整版本: FTP文件上传下载,获取文件列表功能