当前位置:   article > 正文

C# 使用FTP上传文件、下载文件,实现数据传输_c# ftp

c# ftp

FTP操作帮助类:

  1. public class FtpState
  2. {
  3. private ManualResetEvent wait;
  4. private FtpWebRequest request;
  5. private string fileName;
  6. private Exception operationException = null;
  7. string status;
  8. public FtpState()
  9. {
  10. wait = new ManualResetEvent(false);
  11. }
  12. public ManualResetEvent OperationComplete
  13. {
  14. get { return wait; }
  15. }
  16. public FtpWebRequest Request
  17. {
  18. get { return request; }
  19. set { request = value; }
  20. }
  21. public string FileName
  22. {
  23. get { return fileName; }
  24. set { fileName = value; }
  25. }
  26. public Exception OperationException
  27. {
  28. get { return operationException; }
  29. set { operationException = value; }
  30. }
  31. public string StatusDescription
  32. {
  33. get { return status; }
  34. set { status = value; }
  35. }
  36. }
  37. //这个类几乎包含了对FTP常用的方法,有不对的地方,欢迎批评指正
  38. public class FtpClient
  39. {
  40. #region 构造函数
  41. /// <summary>
  42. /// 创建FTP工具
  43. /// <para>
  44. /// 默认不使用SSL,使用二进制传输方式,使用被动模式FTP有两种使用模式:主动和被动。
  45. /// 主动模式要求客户端和服务器端同时打开并且监听一个端口以建立连接。
  46. /// 在这种情况下,客户端由于安装了防火墙会产生一些问题。
  47. /// 所以,创立了被动模式。
  48. /// 被动模式只要求服务器端产生一个监听相应端口的进程,这样就可以绕过客户端安装了防火墙的问题。
  49. /// </para>
  50. /// </summary>
  51. /// <param name="host">主机名称</param>
  52. /// <param name="userId">用户名</param>
  53. /// <param name="password">密码</param>
  54. public FtpClient(string host, string userId, string password)
  55. : this(host, userId, password, 8022, null, false, true, true)
  56. {
  57. }
  58. /// <summary>
  59. /// 创建FTP工具
  60. /// </summary>
  61. /// <param name="host">主机名称</param>
  62. /// <param name="userId">用户名</param>
  63. /// <param name="password">密码</param>
  64. /// <param name="port">端口</param>
  65. /// <param name="enableSsl">允许Ssl</param>
  66. /// <param name="proxy">代理</param>
  67. /// <param name="useBinary">允许二进制</param>
  68. /// <param name="usePassive">允许被动模式</param>
  69. public FtpClient(string host, string userId, string password, int port, IWebProxy proxy, bool enableSsl, bool useBinary, bool usePassive)
  70. {
  71. this.userId = userId;
  72. this.password = password;
  73. MESOperate Dal = new MESOperate();
  74. DataTable dt = Dal.GetServer();
  75. string IP = "";
  76. foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
  77. {
  78. if (_IPAddress.AddressFamily.ToString() == "InterNetwork")
  79. {
  80. IP = _IPAddress.ToString();
  81. }
  82. }
  83. if (IP.Substring(0, 6) == "172.30")
  84. {
  85. this.host = "ftp://" +dt.Rows[0]["SERVER_IP_NEW"].ToString();//产线
  86. }
  87. else
  88. {
  89. this.host = "ftp://" + dt.Rows[0]["SERVER_IP"].ToString();//OA
  90. }
  91. this.port = port;
  92. this.proxy = proxy;
  93. this.enableSsl = enableSsl;
  94. this.useBinary = useBinary;
  95. this.usePassive = usePassive;
  96. this.wait = new ManualResetEvent(false);
  97. }
  98. #endregion
  99. #region 变量
  100. #region 主机
  101. private string host = string.Empty;
  102. /// <summary>
  103. /// 主机
  104. /// </summary>
  105. public string Host
  106. {
  107. get
  108. {
  109. return this.host ?? string.Empty;//如果左操作数为空则返回右操作数,不为空返回左操作数
  110. }
  111. }
  112. #endregion
  113. #region 登录用户名
  114. private string userId = string.Empty;
  115. /// <summary>
  116. /// 登录用户名
  117. /// </summary>
  118. public string UserId
  119. {
  120. get
  121. {
  122. return this.userId;
  123. }
  124. }
  125. #endregion
  126. #region 密码
  127. private string password = string.Empty;
  128. /// <summary>
  129. /// 密码
  130. /// </summary>
  131. public string Password
  132. {
  133. get
  134. {
  135. return this.password;
  136. }
  137. }
  138. #endregion
  139. #region 代理
  140. IWebProxy proxy = null;
  141. /// <summary>
  142. /// 代理
  143. /// </summary>
  144. public IWebProxy Proxy
  145. {
  146. get
  147. {
  148. return this.proxy;
  149. }
  150. set
  151. {
  152. this.proxy = value;
  153. }
  154. }
  155. #endregion
  156. #region 端口
  157. private int port = 8022;
  158. /// <summary>
  159. /// 端口
  160. /// </summary>
  161. public int Port
  162. {
  163. get
  164. {
  165. return port;
  166. }
  167. set
  168. {
  169. this.port = value;
  170. }
  171. }
  172. #endregion
  173. #region 设置是否允许Ssl
  174. private bool enableSsl = false;
  175. /// <summary>
  176. /// EnableSsl
  177. /// </summary>
  178. public bool EnableSsl
  179. {
  180. get
  181. {
  182. return enableSsl;
  183. }
  184. }
  185. #endregion
  186. #region 使用被动模式
  187. private bool usePassive = true;
  188. /// <summary>
  189. /// 被动模式
  190. /// </summary>
  191. public bool UsePassive
  192. {
  193. get
  194. {
  195. return usePassive;
  196. }
  197. set
  198. {
  199. this.usePassive = value;
  200. }
  201. }
  202. #endregion
  203. #region 二进制方式
  204. private bool useBinary = true;
  205. /// <summary>
  206. /// 二进制方式
  207. /// </summary>
  208. public bool UseBinary
  209. {
  210. get
  211. {
  212. return useBinary;
  213. }
  214. set
  215. {
  216. this.useBinary = value;
  217. }
  218. }
  219. #endregion
  220. #region 远端路径
  221. private string remotePath = "/";
  222. /// <summary>
  223. /// 远端路径
  224. /// <para>
  225. /// 返回FTP服务器上的当前路径(可以是 / 或 /a/../ 的形式)
  226. /// </para>
  227. /// </summary>
  228. public string RemotePath
  229. {
  230. get
  231. {
  232. return remotePath;
  233. }
  234. set
  235. {
  236. string result = "/";
  237. if (!string.IsNullOrEmpty(value) && value != "/")
  238. {
  239. result = "/" + value.TrimStart('/').TrimEnd('/') + "/";
  240. }
  241. this.remotePath = result;
  242. }
  243. }
  244. #endregion
  245. private ManualResetEvent wait;
  246. public ManualResetEvent OperationComplete
  247. {
  248. get { return wait; }
  249. }
  250. #endregion
  251. #region 创建一个FTP连接
  252. /// <summary>
  253. /// 创建一个FTP请求
  254. /// </summary>
  255. /// <param name="url">请求地址</param>
  256. /// <param name="method">请求方法</param>
  257. /// <returns>FTP请求</returns>
  258. private FtpWebRequest CreateRequest(string url, string method)
  259. {
  260. //建立连接
  261. FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));
  262. request.Credentials = new NetworkCredential(this.userId, this.password);
  263. request.Proxy = this.proxy;
  264. request.KeepAlive = false;//命令执行完毕之后关闭连接
  265. request.UseBinary = useBinary;
  266. request.UsePassive = usePassive;
  267. request.EnableSsl = enableSsl;
  268. request.Method = method;
  269. return request;
  270. }
  271. #endregion
  272. #region 异步上传
  273. /// <summary>
  274. /// 把文件上传到FTP服务器的RemotePath下
  275. /// </summary>
  276. /// <param name="localFile">本地文件信息</param>
  277. /// <param name="remoteFileName">要保存到FTP文件服务器上的文件名称包含扩展名</param>
  278. /// <param name="isReName">是否重命名</param>
  279. /// <returns></returns>
  280. public bool UploadAsync(string localFile, string remoteFileName,bool isReName,string newName)
  281. {
  282. ManualResetEvent waitObject;
  283. FtpState state = new FtpState();
  284. if (File.Exists(localFile))
  285. {
  286. string url = Host.TrimEnd('/') + RemotePath + remoteFileName;
  287. FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.UploadFile);
  288. state.Request = request;
  289. state.FileName = localFile;
  290. // Get the event to wait on.
  291. waitObject = state.OperationComplete;
  292. request.BeginGetRequestStream(
  293. new AsyncCallback(EndGetStreamCallback), state
  294. );
  295. waitObject.WaitOne();
  296. // The operations either completed or threw an exception.
  297. if (state.OperationException != null)
  298. {
  299. throw state.OperationException;
  300. }
  301. if (isReName)
  302. {
  303. if (this.CheckFileExist(remoteFileName))
  304. {
  305. if (this.Rename(remoteFileName, newName))
  306. {
  307. return true;
  308. }
  309. }
  310. else { throw new Exception(string.Format("远端文件不存在,{0}", remoteFileName)); }
  311. }
  312. else
  313. {
  314. return true;
  315. }
  316. return false;
  317. }
  318. throw new Exception(string.Format("本地文件不存在,文件路径:{0}", localFile));
  319. }
  320. private void EndGetStreamCallback(IAsyncResult ar)
  321. {
  322. FtpState state = (FtpState)ar.AsyncState;
  323. Stream requestStream = null;
  324. // End the asynchronous call to get the request stream.
  325. try
  326. {
  327. requestStream = state.Request.EndGetRequestStream(ar);
  328. // Copy the file contents to the request stream.
  329. const int bufferLength = 2048;
  330. byte[] buffer = new byte[bufferLength];
  331. int count = 0;
  332. int readBytes = 0;
  333. FileStream stream = File.OpenRead(state.FileName);
  334. do
  335. {
  336. readBytes = stream.Read(buffer, 0, bufferLength);
  337. requestStream.Write(buffer, 0, readBytes);
  338. count += readBytes;
  339. }
  340. while (readBytes != 0);
  341. //Console.WriteLine("Writing {0} bytes to the stream.", count);
  342. // IMPORTANT: Close the request stream before sending the request.
  343. requestStream.Close();
  344. // Asynchronously get the response to the upload request.
  345. state.Request.BeginGetResponse(
  346. new AsyncCallback(EndGetResponseCallback),
  347. state
  348. );
  349. }
  350. // Return exceptions to the main application thread.
  351. catch (Exception e)
  352. {
  353. state.OperationException = e;
  354. state.OperationComplete.Set();
  355. //throw new Exception("Could not get the request stream.");
  356. }
  357. }
  358. private void EndGetResponseCallback(IAsyncResult ar)
  359. {
  360. FtpState state = (FtpState)ar.AsyncState;
  361. FtpWebResponse response = null;
  362. try
  363. {
  364. response = (FtpWebResponse)state.Request.EndGetResponse(ar);
  365. response.Close();
  366. state.StatusDescription = response.StatusDescription;
  367. // Signal the main application thread that
  368. // the operation is complete.
  369. state.OperationComplete.Set();
  370. }
  371. // Return exceptions to the main application thread.
  372. catch (Exception e)
  373. {
  374. state.OperationException = e;
  375. state.OperationComplete.Set();
  376. //throw new Exception("Error getting response.");
  377. }
  378. }
  379. #endregion
  380. #region 上传一个文件到远端路径下
  381. /// <summary>
  382. /// 把文件上传到FTP服务器的RemotePath下
  383. /// </summary>
  384. /// <param name="localFile">本地文件信息</param>
  385. /// <param name="remoteFileName">要保存到FTP文件服务器上的文件名称包含扩展名</param>
  386. public bool Upload(FileInfo localFile, string remoteFileName)
  387. {
  388. bool result = false;
  389. if (localFile.Exists)
  390. {
  391. string url = Host.TrimEnd('/') + RemotePath + remoteFileName;
  392. FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.UploadFile);
  393. //上传数据
  394. using (Stream rs = request.GetRequestStream())
  395. {
  396. using (FileStream fs = localFile.OpenRead())
  397. {
  398. byte[] buffer = new byte[4096];//4K
  399. int count = fs.Read(buffer, 0, buffer.Length);//每次从流中读4个字节再写入缓冲区
  400. while (count > 0)
  401. {
  402. rs.Write(buffer, 0, count);
  403. count = fs.Read(buffer, 0, buffer.Length);
  404. }
  405. fs.Close();
  406. result = true;
  407. }
  408. }
  409. return result;
  410. }
  411. throw new Exception(string.Format("本地文件不存在,文件路径:{0}", localFile.FullName));
  412. }
  413. #endregion
  414. #region 从FTP服务器上下载文件
  415. /// <summary>
  416. /// 从当前目录下下载文件
  417. /// <para>
  418. /// 如果本地文件存在,则从本地文件结束的位置开始下载.
  419. /// </para>
  420. /// </summary>
  421. /// <param name="serverName">服务器上的文件名称</param>
  422. /// <param name="localName">本地文件名称</param>
  423. /// <returns>返回一个值,指示是否下载成功</returns>
  424. public bool Download(string serverName, string localName)
  425. {
  426. try
  427. {
  428. bool result = false;
  429. //string tempfilename = Path.GetDirectoryName(localName) + @"\" + Path.GetFileNameWithoutExtension(localName) + ".tmp";
  430. if (File.Exists(localName)) return true;
  431. using (FileStream fs = new FileStream(localName, FileMode.OpenOrCreate)) //创建或打开本地文件
  432. {
  433. //建立连接
  434. string url = Host.TrimEnd('/') + RemotePath + serverName;
  435. FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.DownloadFile);
  436. request.ContentOffset = fs.Length;
  437. using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
  438. {
  439. fs.Position = fs.Length;
  440. byte[] buffer = new byte[4096];//4K
  441. int count = response.GetResponseStream().Read(buffer, 0, buffer.Length);
  442. while (count > 0)
  443. {
  444. fs.Write(buffer, 0, count);
  445. count = response.GetResponseStream().Read(buffer, 0, buffer.Length);
  446. }
  447. response.GetResponseStream().Close();
  448. }
  449. result = true;
  450. }
  451. return result;
  452. }
  453. catch (Exception ex) { throw ex; }
  454. }
  455. #endregion
  456. #region 重命名FTP服务器上的文件
  457. /// <summary>
  458. /// 文件更名
  459. /// </summary>
  460. /// <param name="oldFileName">原文件名</param>
  461. /// <param name="newFileName">新文件名</param>
  462. /// <returns>返回一个值,指示更名是否成功</returns>
  463. public bool Rename(string oldFileName, string newFileName)
  464. {
  465. bool result = false;
  466. //建立连接
  467. string url = Host.TrimEnd('/') + RemotePath + oldFileName;
  468. FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.Rename);
  469. request.RenameTo = newFileName;
  470. using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
  471. {
  472. result = true;
  473. }
  474. return result;
  475. }
  476. #endregion
  477. #region 从当前目录下获取文件列表
  478. /// <summary>
  479. /// 获取当前目录下文件列表
  480. /// </summary>
  481. /// <returns></returns>
  482. public List<string> GetFileList()
  483. {
  484. try
  485. {
  486. List<string> result = new List<string>();
  487. //建立连接
  488. string url = Host.TrimEnd('/') + RemotePath;
  489. FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.ListDirectory);
  490. using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
  491. {
  492. StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.Default);//中文文件名
  493. string line = reader.ReadLine();
  494. while (line != null)
  495. {
  496. result.Add(line);
  497. line = reader.ReadLine();
  498. }
  499. }
  500. return result;
  501. }
  502. catch (Exception ex) { throw ex; }
  503. }
  504. #endregion
  505. #region 从FTP服务器上获取文件和文件夹列表
  506. /// <summary>
  507. /// 获取详细列表
  508. /// </summary>
  509. /// <returns></returns>
  510. public List<string> GetFileDetails()
  511. {
  512. List<string> result = new List<string>();
  513. //建立连接
  514. string url = Host.TrimEnd('/') + RemotePath;
  515. FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.ListDirectoryDetails);
  516. using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
  517. {
  518. StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.Default);//中文文件名
  519. string line = reader.ReadLine();
  520. while (line != null)
  521. {
  522. result.Add(line);
  523. line = reader.ReadLine();
  524. }
  525. }
  526. return result;
  527. }
  528. public List<string> GetFileDetails(string remotepath)
  529. {
  530. List<string> result = new List<string>();
  531. //建立连接
  532. string url = Host.TrimEnd('/') + remotepath;
  533. FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.ListDirectoryDetails);
  534. using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
  535. {
  536. StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.Default);//中文文件名
  537. string line = reader.ReadLine();
  538. while (line != null)
  539. {
  540. result.Add(line);
  541. line = reader.ReadLine();
  542. }
  543. }
  544. return result;
  545. }
  546. #endregion
  547. #region 从FTP服务器上删除文件
  548. /// <summary>
  549. /// 删除FTP服务器上的文件
  550. /// </summary>
  551. /// <param name="fileName">文件名称</param>
  552. /// <returns>返回一个值,指示是否删除成功</returns>
  553. public bool DeleteFile(string fileName)
  554. {
  555. bool result = false;
  556. //建立连接
  557. string url = Host.TrimEnd('/') + RemotePath + fileName;
  558. FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.DeleteFile);
  559. using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
  560. {
  561. result = true;
  562. }
  563. return result;
  564. }
  565. #endregion
  566. #region 在FTP服务器上创建目录
  567. /// <summary>
  568. /// 在当前目录下创建文件夹
  569. /// </summary>
  570. /// <param name="dirName">文件夹名称</param>
  571. /// <returns>返回一个值,指示是否创建成功</returns>
  572. public bool MakeDirectory(string dirName)
  573. {
  574. bool result = false;
  575. //建立连接
  576. string url = Host.TrimEnd('/') + RemotePath + dirName;
  577. FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.MakeDirectory);
  578. using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
  579. {
  580. result = true;
  581. }
  582. return result;
  583. }
  584. #endregion
  585. #region 从FTP服务器上删除目录
  586. /// <summary>
  587. /// 删除文件夹
  588. /// </summary>
  589. /// <param name="dirName">文件夹名称</param>
  590. /// <returns>返回一个值,指示是否删除成功</returns>
  591. public bool DeleteDirectory(string dirName)
  592. {
  593. bool result = false;
  594. //建立连接
  595. string url = Host.TrimEnd('/') + RemotePath + dirName;
  596. FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.RemoveDirectory);
  597. using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
  598. {
  599. result = true;
  600. }
  601. return result;
  602. }
  603. #endregion
  604. #region 从FTP服务器上获取文件大小
  605. /// <summary>
  606. /// 获取文件大小
  607. /// </summary>
  608. /// <param name="fileName"></param>
  609. /// <returns></returns>
  610. public long GetFileSize(string fileName)
  611. {
  612. long result = 0;
  613. //建立连接
  614. string url = Host.TrimEnd('/') + RemotePath + fileName;
  615. FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.GetFileSize);
  616. using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
  617. {
  618. result = response.ContentLength;
  619. }
  620. return result;
  621. }
  622. #endregion
  623. #region 给FTP服务器上的文件追加内容
  624. /// <summary>
  625. /// 给FTP服务器上的文件追加内容
  626. /// </summary>
  627. /// <param name="localFile">本地文件</param>
  628. /// <param name="remoteFileName">FTP服务器上的文件</param>
  629. /// <returns>返回一个值,指示是否追加成功</returns>
  630. public bool Append(FileInfo localFile, string remoteFileName)
  631. {
  632. if (localFile.Exists)
  633. {
  634. using (FileStream fs = new FileStream(localFile.FullName, FileMode.Open))
  635. {
  636. return Append(fs, remoteFileName);
  637. }
  638. }
  639. throw new Exception(string.Format("本地文件不存在,文件路径:{0}", localFile.FullName));
  640. }
  641. /// <summary>
  642. /// 给FTP服务器上的文件追加内容
  643. /// </summary>
  644. /// <param name="stream">数据流(可通过设置偏移来实现从特定位置开始上传)</param>
  645. /// <param name="remoteFileName">FTP服务器上的文件</param>
  646. /// <returns>返回一个值,指示是否追加成功</returns>
  647. public bool Append(Stream stream, string remoteFileName)
  648. {
  649. bool result = false;
  650. if (stream != null && stream.CanRead)
  651. {
  652. //建立连接
  653. string url = Host.TrimEnd('/') + RemotePath + remoteFileName;
  654. FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.AppendFile);
  655. using (Stream rs = request.GetRequestStream())
  656. {
  657. //上传数据
  658. byte[] buffer = new byte[4096];//4K
  659. int count = stream.Read(buffer, 0, buffer.Length);
  660. while (count > 0)
  661. {
  662. rs.Write(buffer, 0, count);
  663. count = stream.Read(buffer, 0, buffer.Length);
  664. }
  665. result = true;
  666. }
  667. }
  668. return result;
  669. }
  670. #endregion
  671. #region 获取FTP服务器上的当前路径
  672. /// <summary>
  673. /// 获取FTP服务器上的当前路径
  674. /// </summary>
  675. public string CurrentDirectory
  676. {
  677. get
  678. {
  679. string result = string.Empty;
  680. string url = Host.TrimEnd('/') + RemotePath;
  681. FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.PrintWorkingDirectory);
  682. using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
  683. {
  684. string temp = response.StatusDescription;
  685. int start = temp.IndexOf('"') + 1;
  686. int end = temp.LastIndexOf('"');
  687. if (end >= start)
  688. {
  689. result = temp.Substring(start, end - start);
  690. }
  691. }
  692. return result;
  693. }
  694. }
  695. #endregion
  696. #region 检查当前路径上是否存在某个文件
  697. /// <summary>
  698. /// 检查文件是否存在
  699. /// </summary>
  700. /// <param name="fileName">要检查的文件名</param>
  701. /// <returns>返回一个值,指示要检查的文件是否存在</returns>
  702. public bool CheckFileExist(string fileName)
  703. {
  704. bool result = false;
  705. if (fileName != null && fileName.Trim().Length > 0)
  706. {
  707. fileName = fileName.Trim();
  708. List<string> files = GetFileList();
  709. if (files != null && files.Count > 0)
  710. {
  711. if (files.Count(q => q.ToLower() == fileName.ToLower()) > 0)
  712. result = true;
  713. }
  714. }
  715. return result;
  716. }
  717. #endregion
  718. /// <summary>
  719. /// 判断当前目录下指定的子目录是否存在
  720. /// </summary>
  721. /// <param name="RemoteDirectoryName">指定的目录名</param>
  722. public bool CheckDirectoryExist(string rootDir, string RemoteDirectoryName)
  723. {
  724. string[] dirList = GetDirectoryList(rootDir);//获取子目录
  725. if (dirList.Length > 0)
  726. {
  727. foreach (string str in dirList)
  728. {
  729. if (str.Trim() == RemoteDirectoryName.Trim())
  730. {
  731. return true;
  732. }
  733. }
  734. }
  735. return false;
  736. }
  737. //获取子目录
  738. public string[] GetDirectoryList(string dirName)
  739. {
  740. string[] drectory = GetFileDetails(dirName).ToArray();
  741. List<string> strList = new List<string>();
  742. if (drectory.Length > 0)
  743. {
  744. foreach (string str in drectory)
  745. {
  746. if (str.Trim().Length == 0)
  747. continue;
  748. //会有两种格式的详细信息返回
  749. //一种包含<DIR>
  750. //一种第一个字符串是drwxerwxx这样的权限操作符号
  751. //现在写代码包容两种格式的字符串
  752. if (str.Trim().Contains("<DIR>"))
  753. {
  754. strList.Add(str.Substring(39).Trim());
  755. }
  756. else
  757. {
  758. if (str.Trim().Substring(0, 1).ToUpper() == "D")
  759. {
  760. strList.Add(str.Substring(55).Trim());
  761. }
  762. }
  763. }
  764. }
  765. return strList.ToArray();
  766. }
  767. }

上传文件的方法调用:

  1. private void btnUpload_Click(object sender, EventArgs e)
  2. {
  3. if (string.IsNullOrEmpty(txtLabelTypeModel.Text))
  4. {
  5. AppendTextColorful("Model is null", Color.Red, true); return;
  6. }
  7. else
  8. {
  9. if (!string.IsNullOrEmpty(txtLabelTypeLabelFile.Text)&&!string.IsNullOrEmpty(txtLabelTypeLabelName.Text))
  10. {
  11. UploadLabel_new(txtLabelTypeModel.Text, txtLabelTypeLabelFile.Text, txtLabelTypeLabelName.Text);
  12. }
  13. }
  14. }
  15. private void UploadLabel(string remotePath,string localFile,string remoteFileName)
  16. {
  17. FtpClient ftp = new FtpClient(labelServerInfo.LabelServerIp, labelServerInfo.LabelServerUser, labelServerInfo.LabelServerPassWord);
  18. if (!ftp.CheckDirectoryExist(ftp.RemotePath, remotePath))
  19. {
  20. string remotepath = "/" + remotePath + "/";
  21. if (!ftp.MakeDirectory(remotepath))
  22. {
  23. AppendTextColorful("Create Remote Path Error", Color.Red, true);
  24. }
  25. }
  26. else
  27. {
  28. string remotepath = "/" + remotePath + "/";
  29. ftp.RemotePath = remotepath;
  30. }
  31. ftp.RemotePath = "/" + remotePath + "/";
  32. if (ftp.CheckFileExist(remoteFileName))
  33. {
  34. if (DialogResult.Yes != MessageBox.Show("Remote File is Exist, Override ?", "Message:", MessageBoxButtons.YesNo, MessageBoxIcon.Question)) { return; }
  35. if (!ftp.DeleteFile(remoteFileName))
  36. {
  37. AppendTextColorful("Delete Remote File Error", Color.Red, true);
  38. }
  39. if (!ftp.Upload(new FileInfo(localFile), remoteFileName))
  40. {
  41. AppendTextColorful("Upload Remote File Error", Color.Red, true);
  42. }
  43. else
  44. {
  45. AppendTextColorful("Upload Remote File OK", Color.Blue, true);
  46. }
  47. }
  48. else
  49. {
  50. if (!ftp.Upload(new FileInfo(localFile), remoteFileName))
  51. {
  52. AppendTextColorful("Upload Remote File Error", Color.Red, true);
  53. }
  54. else
  55. {
  56. AppendTextColorful("Upload Remote File OK", Color.Blue, true);
  57. }
  58. }
  59. }

下载文件方法:

  1. private void btnDownLoad_Click(object sender, EventArgs e)
  2. {
  3. if (string.IsNullOrEmpty(txtLabelTypeLabelName.Text) || string.IsNullOrEmpty(txtLabelTypeModel.Text))
  4. {
  5. AppendTextColorful("Please Select Data", Color.DarkOrange, true);
  6. return;
  7. }
  8. SaveFileDialog saveFileDialog = new SaveFileDialog();
  9. //saveFileDialog.InitialDirectory = "D:\\";
  10. if (txtLabelTypeLabelName.Text.ToLower().EndsWith(".txt"))
  11. {
  12. saveFileDialog.Filter = " ZPL模板文件 | *.txt";
  13. }
  14. else if (txtLabelTypeLabelName.Text.ToLower().EndsWith(".xls")|| txtLabelTypeLabelName.Text.ToLower().EndsWith(".xlsx"))
  15. {
  16. saveFileDialog.Filter = "Excel模板文件 | *.xls; *.xlsx";
  17. }
  18. else if (txtLabelTypeLabelName.Text.ToLower().EndsWith(".lab"))
  19. {
  20. saveFileDialog.Filter = "CodeSoft模板文件|*.lab";
  21. }
  22. else if (txtLabelTypeLabelName.Text.ToLower().EndsWith(".btw"))
  23. {
  24. saveFileDialog.Filter = "Bartender模板文件|*.btw";
  25. }
  26. saveFileDialog.RestoreDirectory = true;
  27. saveFileDialog.FilterIndex = 1;
  28. saveFileDialog.FileName = txtLabelTypeLabelName.Text;
  29. if (saveFileDialog.ShowDialog() == DialogResult.OK)
  30. {
  31. DownLoadLabel(txtLabelTypeModel.Text,txtLabelTypeLabelName.Text, saveFileDialog.FileName);
  32. }
  33. }
  34. private void DownLoadLabel(string remotePath,string remoteFile,string localFileName)
  35. {
  36. try
  37. {
  38. //string localPath = System.Environment.CurrentDirectory;
  39. FtpClient ftp = new FtpClient(labelServerInfo.LabelServerIp, labelServerInfo.LabelServerUser, labelServerInfo.LabelServerPassWord);
  40. ftp.RemotePath = "/" + remotePath + "/";
  41. //if (!Directory.Exists(localPath + @"\Label\")) Directory.CreateDirectory(localPath + @"\Label\");
  42. //if (File.Exists(localPath + @"\Label\" + txtLabelTypeLabelName.Text))
  43. //File.Delete(localPath + @"\Label\" + txtLabelTypeLabelName.Text);
  44. if (!ftp.CheckFileExist(remoteFile))
  45. {
  46. AppendTextColorful("Remote File Not Exist", Color.Red, true);
  47. return;
  48. }
  49. if (!ftp.Download(remoteFile, localFileName))
  50. {
  51. AppendTextColorful("Download Remote File Error", Color.Red, true);
  52. }
  53. else
  54. {
  55. AppendTextColorful("Download Remote File OK", Color.Blue, true);
  56. }
  57. }
  58. catch (Exception ex) { AppendTextColorful(ex.Message, Color.Red, true); }
  59. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/199812
推荐阅读
相关标签
  

闽ICP备14008679号