FTP文件上传以及获取ftp配置帮助类

来源:互联网 发布:淘宝店铺分析报告 编辑:程序博客网 时间:2024/04/30 02:59

帮助类:

  1. using QSProjectBase;
  2. using Reform.CommonLib;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Text;
  9. namespace Reform.CommonLib
  10. {
  11. /// <summary>
  12. /// ftp操作
  13. /// </summary>
  14. public class FtpHelper
  15. {
  16. /// <summary>
  17. /// 上传文件
  18. /// </summary>
  19. /// <param name="fileName">上传文件的全路径</param>
  20. /// <param name="accessory">上传类</param>
  21. /// <returns></returns>
  22. public static bool UploadFile(FileInfo fileinfo, string ftpPath)
  23. {
  24. try
  25. {
  26. if (fileinfo == null || string.IsNullOrEmpty(ftpPath))
  27. return false;
  28. string url = ftpPath;
  29. if (url.Contains("/") || url.Contains("\\"))
  30. {
  31. var str = url.Split(new Char[] { '/', '\\' });
  32. var dic = url.Replace(str[str.Length - 1], "");
  33. CheckAndMakeDir(dic);
  34. }
  35. System.Net.FtpWebRequest ftp = GetRequest(url);
  36. //设置FTP命令 设置所要执行的FTP命令,
  37. //ftp.Method = System.Net.WebRequestMethods.Ftp.ListDirectoryDetails;//假设此处为显示指定路径下的文件列表
  38. ftp.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
  39. ftp.UseBinary = true;
  40. ftp.UsePassive = true;
  41. ftp.ContentLength = fileinfo.Length;
  42. const int BufferSize = 20480; //缓冲大小设置为20KB
  43. byte[] content = new byte[BufferSize - 1 + 1];
  44. int dataRead;
  45. using (FileStream fs = fileinfo.OpenRead())
  46. {
  47. try
  48. {
  49. using (Stream rs = ftp.GetRequestStream())
  50. {
  51. do
  52. {
  53. dataRead = fs.Read(content, 0, BufferSize);
  54. rs.Write(content, 0, dataRead);
  55. } while (!(dataRead < BufferSize));
  56. rs.Close();
  57. }
  58. }
  59. catch (Exception) { }
  60. finally
  61. {
  62. fs.Close();
  63. }
  64. }
  65. ftp = null;
  66. ////设置FTP命令
  67. //ftp = GetRequest(URI);
  68. //ftp.Method = System.Net.WebRequestMethods.Ftp.Rename; //改名
  69. //ftp.RenameTo = fileinfo.Name;
  70. //try
  71. //{
  72. // ftp.GetResponse();
  73. //}
  74. //catch (Exception ex)
  75. //{
  76. // ftp = GetRequest(URI);
  77. // ftp.Method = System.Net.WebRequestMethods.Ftp.DeleteFile; //删除
  78. // ftp.GetResponse();
  79. //}
  80. //ftp = null;
  81. return true;
  82. }
  83. catch (Exception)
  84. {
  85. return false;
  86. }
  87. }
  88. /// <summary>
  89. /// 上传文件
  90. /// </summary>
  91. /// <param name="fileName">上传文件的全路径</param>
  92. /// <param name="ftpPath">上传的目录(包括文件名)</param>
  93. /// <param name="progressHelper">进度帮助</param>
  94. /// <returns></returns>
  95. public static bool UploadFile(FileInfo fileinfo, string ftpPath, ProgressHelper progressHelper, MessageProgressHandler handler)
  96. {
  97. try
  98. {
  99. if (fileinfo == null || string.IsNullOrEmpty(ftpPath))
  100. return false;
  101. string url = ftpPath;
  102. if (url.Contains("/") || url.Contains("\\"))
  103. {
  104. var str = url.Split(new Char[] { '/', '\\' });
  105. var dic = url.Replace(str[str.Length - 1], "");
  106. CheckAndMakeDir(dic);
  107. }
  108. System.Net.FtpWebRequest ftp = GetRequest(url);
  109. //设置FTP命令 设置所要执行的FTP命令,
  110. //ftp.Method = System.Net.WebRequestMethods.Ftp.ListDirectoryDetails;//假设此处为显示指定路径下的文件列表
  111. ftp.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
  112. ftp.UseBinary = true;
  113. ftp.UsePassive = false;
  114. ftp.ContentLength = fileinfo.Length;
  115. const int BufferSize = 20480; //缓冲大小设置为20KB
  116. byte[] content = new byte[BufferSize - 1 + 1];
  117. int dataRead;
  118. using (FileStream fs = fileinfo.OpenRead())
  119. {
  120. long fileLen = fs.Length;
  121. if (progressHelper != null && handler != null)
  122. {
  123. progressHelper.SetProgress(handler, "正在上传...", 0);
  124. }
  125. try
  126. {
  127. long proValue = 0;
  128. using (Stream rs = ftp.GetRequestStream())
  129. {
  130. do
  131. {
  132. dataRead = fs.Read(content, 0, BufferSize);
  133. rs.Write(content, 0, dataRead);
  134. proValue += dataRead;
  135. if (progressHelper != null && handler != null)
  136. {
  137. progressHelper.SetProgress(handler, "正在上传...", (int)((double)proValue * 100 / fileLen));
  138. }
  139. } while (!(dataRead < BufferSize));
  140. var aa = rs.Length;
  141. rs.Close();
  142. }
  143. }
  144. catch (Exception) { }
  145. finally
  146. {
  147. fs.Close();
  148. }
  149. }
  150. ftp = null;
  151. ////设置FTP命令
  152. //ftp = GetRequest(URI);
  153. //ftp.Method = System.Net.WebRequestMethods.Ftp.Rename; //改名
  154. //ftp.RenameTo = fileinfo.Name;
  155. //try
  156. //{
  157. // ftp.GetResponse();
  158. //}
  159. //catch (Exception ex)
  160. //{
  161. // ftp = GetRequest(URI);
  162. // ftp.Method = System.Net.WebRequestMethods.Ftp.DeleteFile; //删除
  163. // ftp.GetResponse();
  164. //}
  165. //ftp = null;
  166. return true;
  167. }
  168. catch (Exception)
  169. {
  170. return false;
  171. }
  172. }
  173. /// <summary>
  174. /// 下载文件
  175. /// </summary>
  176. /// <param name="localDir">下载到本地(全路径)</param>
  177. /// <param name="accessory">要下载的附件类</param>
  178. public static bool DownloadFile(string localFilePath, string ftpPath)
  179. {
  180. if (string.IsNullOrEmpty(ftpPath)) return false;
  181. if (string.IsNullOrEmpty(localFilePath)) return false;
  182. System.Net.FtpWebRequest ftp = null;
  183. try
  184. {
  185. string Url = ftpPath;
  186. string localDir = new FileInfo(localFilePath).DirectoryName;
  187. if (!Directory.Exists(localDir))
  188. {
  189. Directory.CreateDirectory(localDir);
  190. }
  191. string tmpname = Guid.NewGuid().ToString();
  192. string tmpFilePath = localDir + @"\" + tmpname;
  193. ftp = GetRequest(Url);
  194. // MsgBoxShow.ShowInformation(Url);
  195. ftp.Method = System.Net.WebRequestMethods.Ftp.DownloadFile;
  196. ftp.UseBinary = true;
  197. ftp.UsePassive = false;
  198. using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
  199. {
  200. using (Stream responseStream = response.GetResponseStream())
  201. {
  202. using (FileStream fs = new FileStream(tmpFilePath, FileMode.CreateNew))
  203. {
  204. var aa = ftp.ContentLength;
  205. try
  206. {
  207. byte[] buffer = new byte[20480];
  208. int read = 0;
  209. do
  210. {
  211. read = responseStream.Read(buffer, 0, buffer.Length);
  212. fs.Write(buffer, 0, read);
  213. } while (!(read == 0));
  214. responseStream.Close();
  215. fs.Flush();
  216. fs.Close();
  217. }
  218. catch (Exception)
  219. {
  220. fs.Close();
  221. File.Delete(tmpFilePath);
  222. return false;
  223. }
  224. }
  225. responseStream.Close();
  226. }
  227. response.Close();
  228. }
  229. try
  230. {
  231. File.Delete(localFilePath);
  232. File.Move(tmpFilePath, localFilePath);
  233. ftp = null;
  234. }
  235. catch (Exception)
  236. {
  237. File.Delete(tmpFilePath);
  238. return false;
  239. }
  240. ftp = null;
  241. return true;
  242. }
  243. catch (WebException e)
  244. {
  245. Common_LogManager.RecordLog(LogType.Error, e.Message, e);
  246. if (e.Status == WebExceptionStatus.ProtocolError)
  247. {
  248. Console.WriteLine("Status Code : {0}", ((FtpWebResponse)e.Response).StatusCode);
  249. Console.WriteLine("Status Description : {0}", ((FtpWebResponse)e.Response).StatusDescription);
  250. }
  251. return false;
  252. }
  253. }
  254. /// <summary>
  255. /// 下载文件,叠加
  256. /// </summary>
  257. /// <param name="localDir">下载到本地(全路径)</param>
  258. /// <param name="accessory">要下载的附件类</param>
  259. public static bool DownloadFileEx(string localFilePath, string ftpPath)
  260. {
  261. if (string.IsNullOrEmpty(ftpPath)) return false;
  262. if (string.IsNullOrEmpty(localFilePath)) return false;
  263. try
  264. {
  265. string Url = ftpPath;
  266. System.Net.FtpWebRequest ftp = GetRequest(Url);
  267. ftp.Method = System.Net.WebRequestMethods.Ftp.DownloadFile;
  268. ftp.UseBinary = true;
  269. ftp.UsePassive = false;
  270. using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
  271. {
  272. using (Stream responseStream = response.GetResponseStream())
  273. {
  274. using (FileStream fs = new FileStream(localFilePath, FileMode.Append))
  275. {
  276. try
  277. {
  278. byte[] buffer = new byte[20480];
  279. int read = 0;
  280. do
  281. {
  282. read = responseStream.Read(buffer, 0, buffer.Length);
  283. fs.Write(buffer, 0, read);
  284. } while (!(read == 0));
  285. responseStream.Close();
  286. fs.Flush();
  287. fs.Close();
  288. }
  289. catch (Exception)
  290. {
  291. fs.Close();
  292. return false;
  293. }
  294. }
  295. responseStream.Close();
  296. }
  297. response.Close();
  298. }
  299. try
  300. {
  301. ftp = null;
  302. }
  303. catch (Exception)
  304. {
  305. return false;
  306. }
  307. ftp = null;
  308. return true;
  309. }
  310. catch (Exception)
  311. {
  312. return false;
  313. }
  314. }
  315. /// <summary>
  316. /// 下载文件(包含进度)
  317. /// </summary>
  318. /// <param name="localDir">下载到本地(全路径)</param>
  319. /// <param name="accessory">要下载的附件类</param>
  320. public static bool DownloadFile(string localFilePath, string ftpPath, ProgressHelper progressHelper, MessageProgressHandler handler)
  321. {
  322. if (string.IsNullOrEmpty(ftpPath)) return false;
  323. if (string.IsNullOrEmpty(localFilePath)) return false;
  324. try
  325. {
  326. string URI = ftpPath;
  327. string localDir = new FileInfo(localFilePath).DirectoryName;
  328. string tmpname = Guid.NewGuid().ToString();
  329. string tmpFilePath = localDir + @"\" + tmpname;
  330. System.Net.FtpWebRequest ftp = GetRequest(URI);
  331. ftp.Method = System.Net.WebRequestMethods.Ftp.DownloadFile;
  332. ftp.UseBinary = true;
  333. ftp.UsePassive = false;
  334. long fileLen = GetFileSize(ftpPath);
  335. using (WebResponse response = ftp.GetResponse())
  336. {
  337. using (Stream responseStream = response.GetResponseStream())
  338. {
  339. if (progressHelper != null && handler != null)
  340. {
  341. progressHelper.SetProgress(handler, "正在下载...", 0);
  342. }
  343. using (FileStream fs = new FileStream(tmpFilePath, FileMode.OpenOrCreate))
  344. {
  345. try
  346. {
  347. long proValue = 0;
  348. byte[] buffer = new byte[20480];
  349. int read = 0;
  350. do
  351. {
  352. read = responseStream.Read(buffer, 0, buffer.Length);
  353. fs.Write(buffer, 0, read);
  354. proValue += read;
  355. if (progressHelper != null && handler != null)
  356. {
  357. progressHelper.SetProgress(handler, "正在下载...", (int)((double)proValue * 100 / fileLen));
  358. }
  359. } while (!(read == 0));
  360. responseStream.Close();
  361. fs.Flush();
  362. fs.Close();
  363. }
  364. catch (Exception)
  365. {
  366. fs.Close();
  367. File.Delete(tmpFilePath);
  368. return false;
  369. }
  370. }
  371. responseStream.Close();
  372. }
  373. response.Close();
  374. }
  375. try
  376. {
  377. File.Delete(localFilePath);
  378. File.Move(tmpFilePath, localFilePath);
  379. ftp = null;
  380. }
  381. catch (Exception ex)
  382. {
  383. File.Delete(tmpFilePath);
  384. return false;
  385. }
  386. ftp = null;
  387. return true;
  388. }
  389. catch (Exception)
  390. {
  391. return false;
  392. }
  393. }
  394. /// <summary>
  395. /// 删除文件
  396. /// </summary>
  397. /// <param name="accessory">要删除的附件全路径</param>
  398. public static bool DeleteFile(string ftpPath)
  399. {
  400. if (string.IsNullOrEmpty(ftpPath)) return false;
  401. try
  402. {
  403. string URI = ftpPath;
  404. System.Net.FtpWebRequest ftp = GetRequest(URI);
  405. ftp.Method = System.Net.WebRequestMethods.Ftp.DeleteFile;
  406. ftp.UseBinary = true;
  407. ftp.UsePassive = false;
  408. using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
  409. {
  410. using (Stream responseStream = response.GetResponseStream())
  411. {
  412. responseStream.Close();
  413. }
  414. response.Close();
  415. }
  416. ftp = null;
  417. return true;
  418. }
  419. catch (Exception)
  420. {
  421. return false;
  422. }
  423. }
  424. /// <summary>
  425. /// 搜索远程文件
  426. /// </summary>
  427. /// <param name="targetDir">文件夹</param>
  428. /// <param name="SearchPattern">搜索模式</param>
  429. /// <returns></returns>
  430. public static List<string> ListDirectory(string targetDir, string SearchPattern)
  431. {
  432. List<string> result = new List<string>();
  433. try
  434. {
  435. string URI = targetDir + "/" + SearchPattern;
  436. System.Net.FtpWebRequest ftp = GetRequest(URI);
  437. ftp.Method = System.Net.WebRequestMethods.Ftp.ListDirectory;
  438. ftp.UsePassive = true;
  439. ftp.UseBinary = true;
  440. string str = GetStringResponse(ftp);
  441. str = str.Replace("\r\n", "\r").TrimEnd('\r');
  442. str = str.Replace("\n", "\r");
  443. if (str != string.Empty)
  444. result.AddRange(str.Split('\r'));
  445. return result;
  446. }
  447. catch { }
  448. return null;
  449. }
  450. private static string GetStringResponse(FtpWebRequest ftp)
  451. {
  452. string result = "";
  453. using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
  454. {
  455. long size = response.ContentLength;
  456. using (Stream datastream = response.GetResponseStream())
  457. {
  458. using (StreamReader sr = new StreamReader(datastream, System.Text.Encoding.Default))
  459. {
  460. result = sr.ReadToEnd();
  461. sr.Close();
  462. }
  463. datastream.Close();
  464. }
  465. response.Close();
  466. }
  467. return result;
  468. }
  469. public static void CheckAndMakeDir(string dirName)
  470. {
  471. if (string.IsNullOrEmpty(dirName))
  472. {
  473. return;
  474. }
  475. if (dirName.Contains("/") || dirName.Contains("\\"))
  476. {
  477. var str = dirName.Split(new Char[] { '/', '\\' });
  478. if (str.Length == 0 || string.IsNullOrEmpty(str[0]))
  479. {
  480. return;
  481. }
  482. string dir = str[0] + "/";
  483. if (!IsExistsFile(dir))
  484. MakeDir(dir);
  485. for (int i = 1; i < str.Length; i++)
  486. {
  487. if (string.IsNullOrEmpty(str[i]))
  488. {
  489. continue;
  490. }
  491. dir += (str[i] + "/");
  492. if (!IsExistsFile(dir))
  493. MakeDir(dir);
  494. }
  495. }
  496. else
  497. {
  498. if (!IsExistsFile(dirName))
  499. MakeDir(dirName);
  500. }
  501. }
  502. ///
  503. /// 在ftp服务器上创建目录
  504. /// </summary>
  505. /// <param name="dirName">创建的目录名称</param>
  506. public static void MakeDir(string dirName)
  507. {
  508. try
  509. {
  510. System.Net.FtpWebRequest ftp = GetRequest(dirName);
  511. ftp.Method = WebRequestMethods.Ftp.MakeDirectory;
  512. FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
  513. response.Close();
  514. }
  515. catch (Exception ex)
  516. {
  517. //MessageBox.Show(ex.Message);
  518. }
  519. }
  520. /// <summary>
  521. /// 删除目录
  522. /// </summary>
  523. /// <param name="dirName">删除目录名称</param>
  524. public static bool delDir(string dirName)
  525. {
  526. try
  527. {
  528. System.Net.FtpWebRequest ftp = GetRequest(dirName);
  529. ftp.Method = WebRequestMethods.Ftp.RemoveDirectory;
  530. FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
  531. response.Close();
  532. return true;
  533. }
  534. catch (Exception ex)
  535. {
  536. return false;
  537. }
  538. }
  539. /// <summary>
  540. /// 文件重命名
  541. /// </summary>
  542. /// <param name="currentFilename">当前目录名称</param>
  543. /// <param name="newFilename">重命名目录名称</param>
  544. public static bool Rename(string currentFilename, string newFilename)
  545. {
  546. try
  547. {
  548. FileInfo fileInf = new FileInfo(currentFilename);
  549. System.Net.FtpWebRequest ftp = GetRequest(fileInf.Name);
  550. ftp.Method = WebRequestMethods.Ftp.Rename;
  551. ftp.RenameTo = newFilename;
  552. FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
  553. response.Close();
  554. return true;
  555. }
  556. catch (Exception ex)
  557. {
  558. return false;
  559. }
  560. }
  561. private static FtpWebRequest GetRequest(string dirName)
  562. {
  563. string url = "ftp://" + ConfigHepler.FtpServer + "/" + dirName;
  564. //根据服务器信息FtpWebRequest创建类的对象
  565. FtpWebRequest result = (FtpWebRequest)FtpWebRequest.Create(url);
  566. //提供身份验证信息
  567. result.Credentials = new System.Net.NetworkCredential(ConfigHepler.FtpUser, ConfigHepler.FtpPwd);
  568. //设置请求完成之后是否保持到FTP服务器的控制连接,默认值为true
  569. result.KeepAlive = false;
  570. return result;
  571. }
  572. /// <summary>
  573. /// 判断ftp服务器上该目录是否存在
  574. /// </summary>
  575. /// <param name="dirName"></param>
  576. /// <returns></returns>
  577. public static bool IsExistsFile(string dirName)
  578. {
  579. bool flag = true;
  580. try
  581. {
  582. System.Net.FtpWebRequest ftp = GetRequest(dirName);
  583. ftp.Method = WebRequestMethods.Ftp.ListDirectory;
  584. FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
  585. response.Close();
  586. }
  587. catch (Exception)
  588. {
  589. flag = false;
  590. }
  591. return flag;
  592. }
  593. // 获取文件大小
  594. public static long GetFileSize(string ftpPath)
  595. {
  596. long size = 0;
  597. if (string.IsNullOrEmpty(ftpPath)) return size;
  598. try
  599. {
  600. string URI = ftpPath;
  601. System.Net.FtpWebRequest ftp = GetRequest(URI);
  602. ftp.Method = System.Net.WebRequestMethods.Ftp.GetFileSize;
  603. ftp.UseBinary = true;
  604. ftp.UsePassive = false;
  605. using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
  606. {
  607. size = response.ContentLength;
  608. }
  609. }
  610. catch (Exception)
  611. {
  612. }
  613. return size;
  614. }
  615. }
  616. /// <summary>
  617. /// 从配置文件获取配置信息
  618. /// </summary>
  619. public class ConfigHepler
  620. {
  621. private static string m_FtpServer;
  622. private static string m_FtpUser;
  623. private static string m_FtpPwd;
  624. /// <summary>
  625. /// ftp服务器
  626. /// </summary>
  627. public static string FtpServer
  628. {
  629. get
  630. {
  631. if (string.IsNullOrEmpty(m_FtpServer))
  632. {
  633. string[] ftpConfigs = GlobalVars.FtpConfig.Split(new char[] { ';' });
  634. if (ftpConfigs != null && ftpConfigs.Length > 0)
  635. m_FtpServer = ftpConfigs[0];
  636. }
  637. return m_FtpServer;
  638. }
  639. }
  640. /// <summary>
  641. /// ftp用户名
  642. /// </summary>
  643. public static string FtpUser
  644. {
  645. get
  646. {
  647. if (string.IsNullOrEmpty(m_FtpUser))
  648. {
  649. string[] ftpConfigs = GlobalVars.FtpConfig.Split(new char[] { ';' });
  650. if (ftpConfigs != null && ftpConfigs.Length > 1)
  651. m_FtpUser = ftpConfigs[1];
  652. }
  653. return m_FtpUser;
  654. }
  655. }
  656. /// <summary>
  657. /// ftp密码
  658. /// </summary>
  659. public static string FtpPwd
  660. {
  661. get
  662. {
  663. if (string.IsNullOrEmpty(m_FtpPwd))
  664. {
  665. string[] ftpConfigs = GlobalVars.FtpConfig.Split(new char[] { ';' });
  666. if (ftpConfigs != null && ftpConfigs.Length > 2)
  667. m_FtpPwd = ftpConfigs[2];
  668. }
  669. return m_FtpPwd;
  670. }
  671. }
  672. }
  673. }
复制代码

配置文件配置:


例子:

上传调用例子:

  1. FileInfo fInfo = new FileInfo(txtDoc.Text);
  2. //上传到ftp的完整目录,FTP目录+文件格式+日期+GUID+文件名+文件后缀
  3. ftpPath = M_FTPDIRECTORY + m_Archives.DocType.Replace(".", "") + "/" + DateTime.Now.ToString("yyyyMMdd") + "/" + Guid.NewGuid().ToString() + "/" + m_Archives.DocName + m_Archives.DocType;
  4. bool suc = FtpHelper.UploadFile(fInfo, ftpPath);
原创粉丝点击