ftpOperater.cs 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Net;
  5. using System.Text;
  6. using System.Windows.Forms;
  7. namespace MES_Interface
  8. {
  9. public class ftpOperater
  10. {
  11. public static string FTPAddress = "";
  12. public string DownLoadTo = Environment.GetEnvironmentVariable("windir").Substring(0, 1) + @":\" + "打印标签";
  13. private string ftpServerIP;
  14. private string ftpUser;
  15. private string ftpPwd;
  16. public ftpOperater()
  17. {
  18. string[] FTPInf = Properties.Settings.Default.Properties["FTPAddress"].DefaultValue.ToString().Split('|');
  19. this.ftpServerIP = FTPInf[0];
  20. this.ftpUser = FTPInf[1];
  21. this.ftpPwd = FTPInf[2];
  22. }
  23. public void UpLoadFile(string filepath, string filename)
  24. {
  25. //上传之前判断文件是否存在
  26. string[] filelist = GetFileList();
  27. if (filelist != null)
  28. for (int i = 0; i < filelist.Length; i++)
  29. {
  30. if (filelist[i] == filename)
  31. {
  32. string upload = MessageBox.Show("已存在同名文件,是否覆盖", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question).ToString();
  33. if (upload.ToString() != "Yes")
  34. {
  35. return;
  36. }
  37. }
  38. }
  39. FtpWebRequest reqFTP;
  40. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpServerIP + "/" + filename));
  41. reqFTP.UseBinary = true;
  42. reqFTP.Credentials = new NetworkCredential(ftpUser, ftpPwd);
  43. reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
  44. FileInfo file = new FileInfo(filepath + "/" + filename);
  45. const int BufferSize = 2048;
  46. byte[] content = new byte[BufferSize - 1 + 1];
  47. int dataRead;
  48. using (FileStream fs = file.OpenRead())
  49. {
  50. //把上传的文件写入流
  51. using (Stream rs = reqFTP.GetRequestStream())
  52. {
  53. do
  54. {
  55. //每次读文件流的2KB
  56. dataRead = fs.Read(content, 0, BufferSize);
  57. rs.Write(content, 0, dataRead);
  58. } while (!(dataRead < BufferSize));
  59. rs.Close();
  60. }
  61. fs.Close();
  62. }
  63. }
  64. //获取指定的文件的内容
  65. public string GetFileContent(string filename)
  66. {
  67. FtpWebRequest reqFTP;
  68. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpServerIP + "/" + filename));
  69. reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
  70. reqFTP.UseBinary = true;
  71. reqFTP.Credentials = new NetworkCredential(ftpUser, ftpPwd);
  72. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  73. Stream ftpStream = response.GetResponseStream();
  74. int bufferSize = GetFileContentLength(filename);
  75. byte[] buffer = new byte[bufferSize];
  76. ftpStream.Read(buffer, 0, bufferSize);
  77. ftpStream.Close();
  78. return Encoding.Default.GetString(buffer);
  79. }
  80. //获取指定文件的内容的字节长度
  81. public int GetFileContentLength(string filename)
  82. {
  83. FtpWebRequest reqFTP;
  84. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpServerIP + "/" + filename));
  85. reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
  86. reqFTP.UseBinary = true;
  87. reqFTP.Credentials = new NetworkCredential(ftpUser, ftpPwd);
  88. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  89. Stream ftpStream = response.GetResponseStream();
  90. List<byte> buf = new List<byte>();
  91. while (ftpStream.ReadByte() != -1)
  92. {
  93. buf.Add((byte)ftpStream.ReadByte());
  94. }
  95. ftpStream.Close();
  96. return buf.ToArray().Length * 2;
  97. }
  98. /// <summary>
  99. /// 获取ftp服务器上的文件信息
  100. /// </summary>
  101. /// <returns>存储了所有文件信息的字符串数组</returns>
  102. public string[] GetFileList()
  103. {
  104. string[] downloadFiles;
  105. StringBuilder result = new StringBuilder();
  106. FtpWebRequest reqFTP;
  107. try
  108. {
  109. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpServerIP + "/"));
  110. reqFTP.UseBinary = true;
  111. reqFTP.Credentials = new NetworkCredential(ftpUser, ftpPwd);
  112. reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
  113. WebResponse response = reqFTP.GetResponse();
  114. StreamReader reader = new StreamReader(response.GetResponseStream());
  115. string line = reader.ReadLine();
  116. while (line != null)
  117. {
  118. result.Append(line);
  119. result.Append("\n");
  120. line = reader.ReadLine();
  121. }
  122. result.Remove(result.ToString().LastIndexOf('\n'), 1);
  123. reader.Close();
  124. response.Close();
  125. return result.ToString().Split('\n');
  126. }
  127. catch (Exception ex)
  128. {
  129. System.Windows.Forms.MessageBox.Show("获取文件信息失败:" + ex.Message, "操作失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
  130. downloadFiles = null;
  131. return downloadFiles;
  132. }
  133. }
  134. /// <summary>
  135. /// 获取FTP上指定文件的大小
  136. /// </summary>
  137. /// <param name="filename">文件名</param>
  138. /// <returns>文件大小</returns>
  139. public long GetFileSize(string filename)
  140. {
  141. FtpWebRequest reqFTP;
  142. long fileSize = 0;
  143. try
  144. {
  145. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpServerIP + "/" + filename));
  146. reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
  147. reqFTP.UseBinary = true;
  148. reqFTP.Credentials = new NetworkCredential(ftpUser, ftpPwd);
  149. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  150. Stream ftpStream = response.GetResponseStream();
  151. fileSize = response.ContentLength;
  152. ftpStream.Close();
  153. response.Close();
  154. }
  155. catch (Exception ex)
  156. {
  157. MessageBox.Show("获取文件大小时,出现异常:\n" + ex.Message, "获取文件大小失败!", MessageBoxButtons.OK, MessageBoxIcon.Error);
  158. }
  159. return fileSize;
  160. }
  161. /// <summary>
  162. /// 实现ftp下载操作
  163. /// </summary>
  164. /// <param name="fileName">远程文件名</param>
  165. public string Download(string fileName)
  166. {
  167. FtpWebRequest reqFTP;
  168. //filePath = <<The full path where the file is to be created.>>,
  169. //fileName = <<Name of the file to be created(Need not be the name of the file on FTP server).>>
  170. FileStream outputStream = new FileStream(DownLoadTo + @"\" + fileName, FileMode.OpenOrCreate);
  171. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpServerIP + "/" + fileName));
  172. reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
  173. reqFTP.UseBinary = true;
  174. reqFTP.Credentials = new NetworkCredential(ftpUser, ftpPwd);
  175. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  176. Stream ftpStream = response.GetResponseStream();
  177. long cl = response.ContentLength;
  178. int bufferSize = 2048;
  179. int readCount;
  180. byte[] buffer = new byte[bufferSize];
  181. readCount = ftpStream.Read(buffer, 0, bufferSize);
  182. Encoding encoding = Encoding.UTF8;
  183. Console.WriteLine(encoding.GetString(buffer));
  184. while (readCount > 0)
  185. {
  186. outputStream.Write(buffer, 0, readCount);
  187. readCount = ftpStream.Read(buffer, 0, bufferSize);
  188. }
  189. ftpStream.Close();
  190. outputStream.Close();
  191. response.Close();
  192. return DownLoadTo + @"\" + fileName;
  193. }
  194. }
  195. }