本来这篇博文应该在上周就完成的,可无奈,最近工作比较忙,没有时间写,所以推迟到了今天。可悲的是,今天也没有太多的时间,所以决定给大家贴出源码,不做详细的分析说明,如果有不懂的,可以给我留言,我们共同讨论。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 | using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography; using System.Text; using System.Windows.Forms; namespace UpLoad { class UpLoadFiles { private static string FTPCONSTR = "" ; //FTP的服务器地址,格式为ftp://192.168.1.234:8021/。ip地址和端口换成自己的,这些建议写在配置文件中,方便修改 private static string FTPUSERNAME = "" ; //FTP服务器的用户名 private static string FTPPASSWORD = "" ; //FTP服务器的密码 #region 本地文件上传到FTP服务器 /// <summary> /// 上传文件到远程ftp /// </summary> /// <param name="path">本地的文件目录</param> /// <param name="name">文件名称</param> /// <returns></returns> public static bool UploadFile( string path, string name) { string erroinfo = "" ; FileInfo f = new FileInfo(path); path = path.Replace( "\\" , "/" ); path = FTPCONSTR + "/data/uploadFile/photo/" + name; //这个路径是我要传到ftp目录下的这个目录下 FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create( new Uri(path)); reqFtp.UseBinary = true ; reqFtp.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD); reqFtp.KeepAlive = false ; reqFtp.Method = WebRequestMethods.Ftp.UploadFile; reqFtp.ContentLength = f.Length; int buffLength = 2048; byte [] buff = new byte [buffLength]; int contentLen; FileStream fs = f.OpenRead(); try { Stream strm = reqFtp.GetRequestStream(); contentLen = fs.Read(buff, 0, buffLength); while (contentLen != 0) { strm.Write(buff, 0, contentLen); contentLen = fs.Read(buff, 0, buffLength); } strm.Close(); fs.Close(); erroinfo = "完成" ; return true ; } catch (Exception ex) { erroinfo = string .Format( "因{0},无法完成上传" , ex.Message); return false ; } } /// <summary> /// 上传文件到远程ftp /// </summary> /// <param name="ftpPath">ftp上的文件路径</param> /// <param name="path">本地的文件目录</param> /// <param name="id">文件名</param> /// <returns></returns> public static bool UploadFile( string ftpPath, string path, string id) { string erroinfo = "" ; FileInfo f = new FileInfo(path); path = path.Replace( "\\" , "/" ); bool b = MakeDir(ftpPath); if (b == false ) { return false ; } path = FTPCONSTR + ftpPath + id; FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create( new Uri(path)); reqFtp.UseBinary = true ; reqFtp.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD); reqFtp.KeepAlive = false ; reqFtp.Method = WebRequestMethods.Ftp.UploadFile; reqFtp.ContentLength = f.Length; int buffLength = 2048; byte [] buff = new byte [buffLength]; int contentLen; FileStream fs = f.OpenRead(); try { Stream strm = reqFtp.GetRequestStream(); contentLen = fs.Read(buff, 0, buffLength); while (contentLen != 0) { strm.Write(buff, 0, contentLen); contentLen = fs.Read(buff, 0, buffLength); } strm.Close(); fs.Close(); erroinfo = "完成" ; return true ; } catch (Exception ex) { erroinfo = string .Format( "因{0},无法完成上传" , ex.Message); return false ; } } /// <summary> /// 上传 /// </summary> /// <param name="path">本地的文件目录</param> /// <param name="name">文件名称</param> /// <param name="pb">进度条</param> /// <returns></returns> public static bool UploadFile( string path, string name, ProgressBar pb) { string erroinfo = "" ; float percent = 0; FileInfo f = new FileInfo(path); path = path.Replace( "\\" , "/" ); path = FTPCONSTR + "/data/uploadFile/photo/" + name; FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create( new Uri(path)); reqFtp.UseBinary = true ; reqFtp.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD); reqFtp.KeepAlive = false ; reqFtp.Method = WebRequestMethods.Ftp.UploadFile; reqFtp.ContentLength = f.Length; int buffLength = 2048; byte [] buff = new byte [buffLength]; int contentLen; FileStream fs = f.OpenRead(); int allbye = ( int )f.Length; if (pb != null ) { pb.Maximum = ( int )allbye; } int startbye = 0; try { Stream strm = reqFtp.GetRequestStream(); contentLen = fs.Read(buff, 0, buffLength); while (contentLen != 0) { strm.Write(buff, 0, contentLen); startbye = contentLen + startbye; if (pb != null ) { pb.Value = ( int )startbye; } contentLen = fs.Read(buff, 0, buffLength); percent = ( float )startbye / ( float )allbye * 100; } strm.Close(); fs.Close(); erroinfo = "完成" ; return true ; } catch (Exception ex) { erroinfo = string .Format( "因{0},无法完成上传" , ex.Message); return false ; } } /// <summary> /// 文件上传到ftp /// </summary> /// <param name="ftpPath">ftp的文件路径</param> /// <param name="path">本地的文件目录</param> /// <param name="name">文件名称</param> /// <param name="pb">进度条</param> /// <returns></returns> public static bool UploadFile( string ftpPath, string path, string name, ProgressBar pb) { //path = "ftp://" + UserUtil.serverip + path; string erroinfo = "" ; float percent = 0; FileInfo f = new FileInfo(path); path = path.Replace( "\\" , "/" ); bool b = MakeDir(ftpPath); if (b == false ) { return false ; } path = FTPCONSTR + ftpPath + name; FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create( new Uri(path)); reqFtp.UseBinary = true ; reqFtp.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD); reqFtp.KeepAlive = false ; reqFtp.Method = WebRequestMethods.Ftp.UploadFile; reqFtp.ContentLength = f.Length; int buffLength = 2048; byte [] buff = new byte [buffLength]; int contentLen; FileStream fs = f.OpenRead(); int allbye = ( int )f.Length; //if (pb != null) //{ // pb.Maximum = (int)allbye; //} int startbye = 0; try { Stream strm = reqFtp.GetRequestStream(); contentLen = fs.Read(buff, 0, buffLength); while (contentLen != 0) { strm.Write(buff, 0, contentLen); startbye = contentLen + startbye; percent = ( float )startbye / ( float )allbye * 100; if (percent <= 100) { int i = ( int )percent; if (pb != null ) { pb.BeginInvoke( new updateui(upui), new object [] { allbye, i, pb }); } } contentLen = fs.Read(buff, 0, buffLength); // Console.WriteLine(percent); } strm.Close(); fs.Close(); erroinfo = "完成" ; return true ; } catch (Exception ex) { erroinfo = string .Format( "因{0},无法完成上传" , ex.Message); return false ; } } private delegate void updateui( long rowCount, int i, ProgressBar PB); public static void upui( long rowCount, int i, ProgressBar PB) { try { PB.Value = i; } catch { } } ////上面的代码实现了从ftp服务器下载文件的功能 public static Stream Download( string ftpfilepath) { Stream ftpStream = null ; FtpWebResponse response = null ; try { ftpfilepath = ftpfilepath.Replace( "\\" , "/" ); string url = FTPCONSTR + ftpfilepath; FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create( new Uri(url)); reqFtp.UseBinary = true ; reqFtp.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD); response = (FtpWebResponse)reqFtp.GetResponse(); ftpStream = response.GetResponseStream(); } catch (Exception ee) { if (response != null ) { response.Close(); } MessageBox.Show( "文件读取出错,请确认FTP服务器服务开启并存在该文件" ); } return ftpStream; } #endregion #region 从ftp服务器下载文件 /// <summary> /// 从ftp服务器下载文件的功能 /// </summary> /// <param name="ftpfilepath">ftp下载的地址</param> /// <param name="filePath">存放到本地的路径</param> /// <param name="fileName">保存的文件名称</param> /// <returns></returns> public static bool Download( string ftpfilepath, string filePath, string fileName) { try { filePath = filePath.Replace( "我的电脑\\" , "" ); String onlyFileName = Path.GetFileName(fileName); string newFileName = filePath + onlyFileName; if (File.Exists(newFileName)) { //errorinfo = string.Format("本地文件{0}已存在,无法下载", newFileName); File.Delete(newFileName); //return false; } ftpfilepath = ftpfilepath.Replace( "\\" , "/" ); string url = FTPCONSTR + ftpfilepath; FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create( new Uri(url)); reqFtp.UseBinary = true ; reqFtp.Credentials = new NetworkCredential(FTPUSERNAME, 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(); return true ; } catch (Exception ex) { //errorinfo = string.Format("因{0},无法下载", ex.Message); return false ; } } // /// <summary> /// 从ftp服务器下载文件的功能----带进度条 /// </summary> /// <param name="ftpfilepath">ftp下载的地址</param> /// <param name="filePath">保存本地的地址</param> /// <param name="fileName">保存的名字</param> /// <param name="pb">进度条引用</param> /// <returns></returns> public static bool Download( string ftpfilepath, string filePath, string fileName, ProgressBar pb) { FtpWebRequest reqFtp = null ; FtpWebResponse response = null ; Stream ftpStream = null ; FileStream outputStream = null ; try { filePath = filePath.Replace( "我的电脑\\" , "" ); String onlyFileName = Path.GetFileName(fileName); string newFileName = filePath + onlyFileName; if (File.Exists(newFileName)) { try { File.Delete(newFileName); } catch { } } ftpfilepath = ftpfilepath.Replace( "\\" , "/" ); string url = FTPCONSTR + ftpfilepath; reqFtp = (FtpWebRequest)FtpWebRequest.Create( new Uri(url)); reqFtp.UseBinary = true ; reqFtp.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD); response = (FtpWebResponse)reqFtp.GetResponse(); ftpStream = response.GetResponseStream(); long cl = GetFileSize(url); int bufferSize = 2048; int readCount; byte [] buffer = new byte [bufferSize]; readCount = ftpStream.Read(buffer, 0, bufferSize); outputStream = new FileStream(newFileName, FileMode.Create); float percent = 0; while (readCount > 0) { outputStream.Write(buffer, 0, readCount); readCount = ftpStream.Read(buffer, 0, bufferSize); percent = ( float )outputStream.Length / ( float )cl * 100; if (percent <= 100) { if (pb != null ) { pb.Invoke( new updateui(upui), new object [] { cl, ( int )percent, pb }); } } // pb.Invoke(new updateui(upui), new object[] { cl, outputStream.Length, pb }); } //MessageBoxEx.Show("Download0"); return true ; } catch (Exception ex) { //errorinfo = string.Format("因{0},无法下载", ex.Message); //MessageBoxEx.Show("Download00"); return false ; } finally { //MessageBoxEx.Show("Download2"); if (reqFtp != null ) { reqFtp.Abort(); } if (response != null ) { response.Close(); } if (ftpStream != null ) { ftpStream.Close(); } if (outputStream != null ) { outputStream.Close(); } } } #endregion #region 获得文件的大小 /// <summary> /// 获得文件大小 /// </summary> /// <param name="url">FTP文件的完全路径</param> /// <returns></returns> public static long GetFileSize( string url) { long fileSize = 0; try { FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create( new Uri(url)); reqFtp.UseBinary = true ; reqFtp.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD); reqFtp.Method = WebRequestMethods.Ftp.GetFileSize; FtpWebResponse response = (FtpWebResponse)reqFtp.GetResponse(); fileSize = response.ContentLength; response.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } return fileSize; } #endregion #region 在ftp服务器上创建文件目录 /// <summary> ///在ftp服务器上创建文件目录 /// </summary> /// <param name="dirName">文件目录</param> /// <returns></returns> public static bool MakeDir( string dirName) { try { bool b = RemoteFtpDirExists(dirName); if (b) { return true ; } string url = FTPCONSTR + dirName; FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create( new Uri(url)); reqFtp.UseBinary = true ; // reqFtp.KeepAlive = false; reqFtp.Method = WebRequestMethods.Ftp.MakeDirectory; reqFtp.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD); FtpWebResponse response = (FtpWebResponse)reqFtp.GetResponse(); response.Close(); return true ; } catch (Exception ex) { //errorinfo = string.Format("因{0},无法下载", ex.Message); return false ; } } /// <summary> /// 判断ftp上的文件目录是否存在 /// </summary> /// <param name="path"></param> /// <returns></returns> public static bool RemoteFtpDirExists( string path) { path = FTPCONSTR + path; FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create( new Uri(path)); reqFtp.UseBinary = true ; reqFtp.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD); reqFtp.Method = WebRequestMethods.Ftp.ListDirectory; FtpWebResponse resFtp = null ; try { resFtp = (FtpWebResponse)reqFtp.GetResponse(); FtpStatusCode code = resFtp.StatusCode; //OpeningData resFtp.Close(); return true ; } catch { if (resFtp != null ) { resFtp.Close(); } return false ; } } #endregion #region 从ftp服务器删除文件的功能 /// <summary> /// 从ftp服务器删除文件的功能 /// </summary> /// <param name="fileName"></param> /// <returns></returns> public static bool DeleteFile( string fileName) { try { string url = FTPCONSTR + fileName; FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create( new Uri(url)); reqFtp.UseBinary = true ; reqFtp.KeepAlive = false ; reqFtp.Method = WebRequestMethods.Ftp.DeleteFile; reqFtp.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD); FtpWebResponse response = (FtpWebResponse)reqFtp.GetResponse(); response.Close(); return true ; } catch (Exception ex) { //errorinfo = string.Format("因{0},无法下载", ex.Message); return false ; } } #endregion } } |
这是从FTP文件上传、下载、新建目录以及删除文件的一个类,应该有用的到的地放。关于ftp的配置,如果大家有疑问的话可以去网上查查,如果后期我有时间的话我也会写一写。
版权声明:本文为博主原创文章,若要转载,请注明原处。
分类:
.NET开发
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?