ftpOperater.cs 8.4 KB

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