FTP文件上传下载,获取文件列表功能
窗体设计器
1 #region Windows 窗体设计器生成的代码 2 3 /// <summary> 4 /// 设计器支持所需的方法 - 不要 5 /// 使用代码编辑器修改此方法的内容。 6 /// </summary> 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类
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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 /// <summary> 31 /// 连接ftp 32 /// </summary> 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 /// <summary> 51 /// 获取文件详细目录 52 /// </summary> 53 /// ftppath ftp上文件路径 如:ftp://192.168.1.1//wangqihe 54 /// <returns></returns> 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 /// <summary> 88 /// 只获取ftp文件 89 /// </summary> 90 /// <returns></returns> 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[i].IndexOf("<DIR>"); 98 if (dirPos > 0) 99 { 100 /*判断 Windows 风格*/ 101 m += list[i].Substring(dirPos + 5).Trim() + "\n"; 102 } 103 else if (list[i].Trim().Substring(0, 1).ToUpper() == "D") 104 { 105 /*判断 Unix 风格*/ 106 string dir = list[i].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("<DIR>"); 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 /// <summary> 144 /// 单个文件下载方法 145 /// </summary> 146 /// <param name="adss">保存文件的本地路径</param> 147 /// <param name="ftpadss">下载文件的FTP路径</param> 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[bufferSize];//设置缓存区 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 /// </summary> 182 /// <param name="ftpads">FTP地址路径</param> 183 /// <param name="name">我们所选择的文件或者文件夹名字</param> 184 /// <param name="type">要发送到FTP服务器的命令</param> 185 /// <returns></returns> 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 /// <summary> 218 /// 下载方法KO 219 /// </summary> 220 /// <param name="ftpads">FTP路径</param> 221 /// <param name="name">需要下载文件路径</param> 222 /// <param name="Myads">保存的本地路径</param> 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 <= 2) 230 { 231 if (fullname[fullname.Length - 1] == "") 232 { 233 download(downloadDir + "/" + name, ftpads + name + "/" + name); 234 } 235 } 236 else 237 { 238 string[] onlyname = ftp(ftpads, name, WebRequestMethods.Ftp.ListDirectory); 239 if (!Directory.Exists(downloadDir)) 240 { 241 Directory.CreateDirectory(downloadDir); 242 } 243 foreach (string names in fullname) 244 { 245 //判断是否具有文件夹标识<DIR> 246 if (names.StartsWith("d") && (!names.EndsWith("."))) 247 { 248 string olname = names.Substring(names.IndexOf(':') + 3).TrimStart(); 249 //string olname = names.Split(new string[] { "<DIR>" }, 250 //StringSplitOptions.None)[1].Trim(); 251 downftp(ftpdir, "//" + olname, downloadDir); 252 } 253 else 254 { 255 foreach (string onlynames in onlyname) 256 { 257 if (onlynames == "" || onlynames == " " || names == "") 258 { 259 break; 260 } 261 else 262 { 263 if (names.Contains(" " + onlynames)) 264 { 265 download(downloadDir + "/" + onlynames, ftpads + name + "/" + 266 onlynames); 267 break; 268 } 269 } 270 } 271 } 272 } 273 } 274 275 } 276 #endregion 277 278 279 #region ftp服务器上载文件的功能 string Upload(string data, string filename, string file) 280 //ftp服务器上载文件的功能 281 public string Upload(string data, string filename, string file) 282 { 283 FileInfo fileInf = new FileInfo(filename); 284 string uri = file + "\\" + data; 285 FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); 286 reqFTP.Credentials = new NetworkCredential("wangqihe", "123456");//获取设置与ftp服务器通信凭证 287 // 默认为true,连接不会被关闭 yyyyMMddHHmmss 288 // 在一个命令之后被执行 289 reqFTP.KeepAlive = false; 290 // 指定执行什么命令 291 reqFTP.Method = WebRequestMethods.Ftp.UploadFile; 292 // 上传文件时通知服务器文件的大小 293 reqFTP.ContentLength = fileInf.Length; 294 // 缓冲大小设置为kb 295 int buffLength = 2048; 296 byte[] buff = new byte[buffLength]; 297 int contentLen; 298 // 打开一个文件流(System.IO.FileStream) 去读上传的文件 299 FileStream fs = fileInf.OpenRead(); 300 try 301 { 302 // 把上传的文件写入流 303 Stream strm = reqFTP.GetRequestStream(); 304 // 每次读文件流的kb 305 contentLen = fs.Read(buff, 0, buffLength); 306 int totalDownloadedByte = 0; 307 // 流内容没有结束 308 while (contentLen != 0) 309 { 310 totalDownloadedByte = contentLen + totalDownloadedByte; //更新文件 311 // 把内容从file stream 写入upload stream 312 strm.Write(buff, 0, contentLen); 313 314 contentLen = fs.Read(buff, 0, buffLength); 315 } 316 // 关闭两个流 317 strm.Close(); 318 fs.Close(); 319 return ""; 320 } 321 catch (Exception ex) 322 { 323 return "Upload Error" + ex.Message; 324 } 325 } 326 #endregion 327 328 public static void DeleteFileName(string fileName) 329 { 330 try 331 { 332 string uri = fileName; 333 FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); 334 // 默认为true,连接不会被关闭 335 // 在一个命令之后被执行 336 reqFTP.KeepAlive = false; 337 // 指定执行什么命令 338 reqFTP.Method = WebRequestMethods.Ftp.DeleteFile; 339 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); 340 response.Close(); 341 } 342 catch (Exception ex) 343 { 344 345 } 346 } 347 348 public static string MakeDir(string dirName) 349 { 350 try 351 { 352 string uri = dirName; 353 FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); 354 reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory; 355 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); 356 response.Close(); 357 return ""; 358 } 359 catch (WebException ex) 360 { 361 return "[Make Dir]" + ex.Message; 362 } 363 } 364 //获得文件大小 365 public long GetFileSize(string filename) 366 { 367 long fileSize = 0; 368 try 369 { 370 FileInfo fileInf = new FileInfo(filename); 371 string uri = fileInf.Name; 372 FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); 373 reqFTP.Method = WebRequestMethods.Ftp.GetFileSize; 374 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); 375 fileSize = response.ContentLength; 376 response.Close(); 377 } 378 catch (Exception ex) 379 { 380 MessageBox.Show(ex.Message); 381 } 382 return fileSize; 383 } 384 } 385 }
窗体事件
获取文件列表
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#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
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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); }
基本功能都实现了 有源码