ftpOperater.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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. public void UpLoadFile(string filepath, string filename,string savepath)
  66. {
  67. //目标路径
  68. string targetPath = savepath;
  69. //var file = Directory.GetFiles(targetPath);
  70. string sourceFile = Path.Combine(filepath+@"\", filename);
  71. string destFile = Path.Combine(targetPath, filename);
  72. //获取指定路径下的全部文件名
  73. var file = Directory.GetFiles(targetPath);
  74. string overwrite = "";
  75. for (int i = 0; i < file.Length; i++)
  76. {
  77. if (file[i].Substring(file[i].LastIndexOf(@"\") + 1) == filename)
  78. {
  79. overwrite = MessageBox.Show("已存在名为" + filename + "的文件,是否覆盖", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question).ToString();
  80. break;
  81. }
  82. }
  83. if (overwrite == "Yes" || overwrite == "")
  84. {
  85. //不存在文件的话进行创建
  86. if (!Directory.Exists(targetPath))
  87. Directory.CreateDirectory(targetPath);
  88. //将文件复制到指定位置
  89. File.Copy(sourceFile, destFile, true);
  90. }
  91. }
  92. /// <summary>
  93. /// 获取ftp服务器上的文件信息
  94. /// </summary>
  95. /// <returns>存储了所有文件信息的字符串数组</returns>
  96. public string[] GetFileList()
  97. {
  98. string[] downloadFiles;
  99. StringBuilder result = new StringBuilder();
  100. FtpWebRequest reqFTP;
  101. try
  102. {
  103. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpServerIP + "/"));
  104. reqFTP.UseBinary = true;
  105. reqFTP.Credentials = new NetworkCredential(ftpUser, ftpPwd);
  106. reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
  107. WebResponse response = reqFTP.GetResponse();
  108. StreamReader reader = new StreamReader(response.GetResponseStream());
  109. string line = reader.ReadLine();
  110. while (line != null)
  111. {
  112. result.Append(line);
  113. result.Append("\n");
  114. line = reader.ReadLine();
  115. }
  116. result.Remove(result.ToString().LastIndexOf('\n'), 1);
  117. reader.Close();
  118. response.Close();
  119. return result.ToString().Split('\n');
  120. }
  121. catch (Exception ex)
  122. {
  123. System.Windows.Forms.MessageBox.Show("获取文件信息失败:" + ex.Message, "操作失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
  124. downloadFiles = null;
  125. return downloadFiles;
  126. }
  127. }
  128. //获取指定的文件的内容
  129. public string GetFileContent(string filename)
  130. {
  131. FtpWebRequest reqFTP;
  132. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpServerIP + "/" + filename));
  133. reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
  134. reqFTP.UseBinary = true;
  135. reqFTP.Credentials = new NetworkCredential(ftpUser, ftpPwd);
  136. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  137. Stream ftpStream = response.GetResponseStream();
  138. int bufferSize = GetFileContentLength(filename);
  139. byte[] buffer = new byte[bufferSize];
  140. ftpStream.Read(buffer, 0, bufferSize);
  141. ftpStream.Close();
  142. return Encoding.Default.GetString(buffer);
  143. }
  144. //获取指定文件的内容的字节长度
  145. public int GetFileContentLength(string filename)
  146. {
  147. FtpWebRequest reqFTP;
  148. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpServerIP + "/" + filename));
  149. reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
  150. reqFTP.UseBinary = true;
  151. reqFTP.Credentials = new NetworkCredential(ftpUser, ftpPwd);
  152. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  153. Stream ftpStream = response.GetResponseStream();
  154. List<byte> buf = new List<byte>();
  155. while (ftpStream.ReadByte() != -1)
  156. {
  157. buf.Add((byte)ftpStream.ReadByte());
  158. }
  159. ftpStream.Close();
  160. return buf.ToArray().Length * 2;
  161. }
  162. /// <summary>
  163. /// 获取FTP上指定文件的大小
  164. /// </summary>
  165. /// <param name="filename">文件名</param>
  166. /// <returns>文件大小</returns>
  167. public long GetFileSize(string filename)
  168. {
  169. FtpWebRequest reqFTP;
  170. long fileSize = 0;
  171. try
  172. {
  173. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpServerIP + "/" + filename));
  174. reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
  175. reqFTP.UseBinary = true;
  176. reqFTP.Credentials = new NetworkCredential(ftpUser, ftpPwd);
  177. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  178. Stream ftpStream = response.GetResponseStream();
  179. fileSize = response.ContentLength;
  180. ftpStream.Close();
  181. response.Close();
  182. }
  183. catch (Exception ex)
  184. {
  185. MessageBox.Show("获取文件大小时,出现异常:\n" + ex.Message, "获取文件大小失败!", MessageBoxButtons.OK, MessageBoxIcon.Error);
  186. }
  187. return fileSize;
  188. }
  189. /// <summary>
  190. /// 实现ftp下载操作
  191. /// </summary>
  192. /// <param name="fileName">远程文件名</param>
  193. public string Download(string fileName)
  194. {
  195. FtpWebRequest reqFTP;
  196. try
  197. {
  198. FileStream outputStream = new FileStream(DownLoadTo + @"\" + fileName, FileMode.Create);
  199. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpServerIP + "/" + fileName));
  200. reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
  201. reqFTP.UseBinary = true;
  202. reqFTP.Credentials = new NetworkCredential(ftpUser, ftpPwd);
  203. reqFTP.UsePassive = true;
  204. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  205. Stream ftpStream = response.GetResponseStream();
  206. long cl = response.ContentLength;
  207. int bufferSize = 2048;
  208. int readCount;
  209. byte[] buffer = new byte[bufferSize];
  210. readCount = ftpStream.Read(buffer, 0, bufferSize);
  211. while (readCount > 0)
  212. {
  213. outputStream.Write(buffer, 0, readCount);
  214. readCount = ftpStream.Read(buffer, 0, bufferSize);
  215. }
  216. ftpStream.Close();
  217. outputStream.Close();
  218. response.Close();
  219. return DownLoadTo + @"\" + fileName;
  220. }
  221. catch (Exception ex)
  222. {
  223. MessageBox.Show(ex.Message);
  224. return "";
  225. }
  226. }
  227. /// <summary>
  228. /// 删除文件
  229. /// </summary>
  230. /// <param name="fileName"></param>
  231. public void Delete(string fileName)
  232. {
  233. try
  234. {
  235. FtpWebRequest reqFTP;
  236. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpServerIP + "/" + fileName));
  237. reqFTP.KeepAlive = false;
  238. reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
  239. reqFTP.UseBinary = true;
  240. reqFTP.Credentials = new NetworkCredential(ftpUser, ftpPwd);
  241. reqFTP.UsePassive = true;
  242. string result = String.Empty;
  243. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  244. long size = response.ContentLength;
  245. Stream datastream = response.GetResponseStream();
  246. StreamReader sr = new StreamReader(datastream);
  247. result = sr.ReadToEnd();
  248. sr.Close();
  249. datastream.Close();
  250. response.Close();
  251. //Buffer.Log(string.Format("Ftp文件{1}删除成功!", DateTime.Now.ToString(), fileName));
  252. }
  253. catch (Exception ex)
  254. {
  255. throw ex;
  256. }
  257. }
  258. }
  259. }