ftpOperater.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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 FTPInf;
  15. private string ftpServerIP;
  16. private string ftpUser;
  17. private string ftpPwd;
  18. bool status = false;
  19. public ftpOperater()
  20. {
  21. //string[] FTPInf = Properties.Settings.Default.Properties["FTPAddress"].DefaultValue.ToString().Split('|');
  22. //this.ftpServerIP = FTPInf[0];
  23. //this.ftpUser = FTPInf[1];
  24. //this.ftpPwd = FTPInf[2];
  25. string FTPInf = Properties.Settings.Default.Properties["FTPAddress"].DefaultValue.ToString();
  26. //连接共享文件夹
  27. status = BaseUtil.connectState(FTPInf);
  28. }
  29. #region
  30. public void UpLoadFile(string filepath, string filename)
  31. {
  32. //上传之前判断文件是否存在
  33. string[] filelist = GetFileList();
  34. if (filelist != null)
  35. for (int i = 0; i < filelist.Length; i++)
  36. {
  37. if (filelist[i] == filename)
  38. {
  39. string upload = MessageBox.Show("已存在同名文件,是否覆盖", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question).ToString();
  40. if (upload.ToString() != "Yes")
  41. {
  42. return;
  43. }
  44. }
  45. }
  46. FtpWebRequest reqFTP;
  47. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpServerIP + "/" + filename));
  48. reqFTP.UseBinary = true;
  49. reqFTP.Credentials = new NetworkCredential(ftpUser, ftpPwd);
  50. reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
  51. FileInfo file = new FileInfo(filepath + "/" + filename);
  52. const int BufferSize = 2048;
  53. byte[] content = new byte[BufferSize - 1 + 1];
  54. int dataRead;
  55. using (FileStream fs = file.OpenRead())
  56. {
  57. //把上传的文件写入流
  58. using (Stream rs = reqFTP.GetRequestStream())
  59. {
  60. do
  61. {
  62. //每次读文件流的2KB
  63. dataRead = fs.Read(content, 0, BufferSize);
  64. rs.Write(content, 0, dataRead);
  65. } while (!(dataRead < BufferSize));
  66. rs.Close();
  67. }
  68. fs.Close();
  69. }
  70. }
  71. #endregion
  72. public void UpLoadFile(string filepath, string filename,string savepath)
  73. {
  74. if (status)
  75. {
  76. //目标路径
  77. string targetPath = savepath;
  78. //var file = Directory.GetFiles(targetPath);
  79. string sourceFile = Path.Combine(filepath + @"\", filename);
  80. string destFile = Path.Combine(targetPath + @"\", filename);
  81. //获取指定路径下的全部文件名
  82. var file = Directory.GetFiles(targetPath);
  83. string overwrite = "";
  84. for (int i = 0; i < file.Length; i++)
  85. {
  86. if (file[i].Substring(file[i].LastIndexOf(@"\") + 1) == filename)
  87. {
  88. overwrite = MessageBox.Show("已存在名为" + filename + "的文件,是否覆盖", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question).ToString();
  89. break;
  90. }
  91. }
  92. if (overwrite == "Yes" || overwrite == "")
  93. {
  94. //不存在文件的话进行创建
  95. if (!Directory.Exists(targetPath))
  96. Directory.CreateDirectory(targetPath);
  97. //将文件复制到指定位置
  98. File.Copy(sourceFile, destFile, true);
  99. }
  100. //string sourceFile = Path.Combine(filepath+@"\", filename);
  101. ////共享文件夹的目录
  102. //DirectoryInfo theFolder = new DirectoryInfo(savepath);
  103. ////获取保存文件的路径
  104. //string fielpath = theFolder.ToString() + @"\";
  105. ////执行方法
  106. //BaseUtil.Transport(sourceFile, fielpath, filename);
  107. }
  108. else
  109. {
  110. //ListBox1.Items.Add("未能连接!");
  111. MessageBox.Show("共享文件连接错误");
  112. }
  113. }
  114. /// <summary>
  115. /// 获取ftp服务器上的文件信息
  116. /// </summary>
  117. /// <returns>存储了所有文件信息的字符串数组</returns>
  118. public string[] GetFileList()
  119. {
  120. string[] downloadFiles;
  121. StringBuilder result = new StringBuilder();
  122. FtpWebRequest reqFTP;
  123. try
  124. {
  125. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpServerIP + "/"));
  126. reqFTP.UseBinary = true;
  127. reqFTP.Credentials = new NetworkCredential(ftpUser, ftpPwd);
  128. reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
  129. WebResponse response = reqFTP.GetResponse();
  130. StreamReader reader = new StreamReader(response.GetResponseStream());
  131. string line = reader.ReadLine();
  132. while (line != null)
  133. {
  134. result.Append(line);
  135. result.Append("\n");
  136. line = reader.ReadLine();
  137. }
  138. result.Remove(result.ToString().LastIndexOf('\n'), 1);
  139. reader.Close();
  140. response.Close();
  141. return result.ToString().Split('\n');
  142. }
  143. catch (Exception ex)
  144. {
  145. System.Windows.Forms.MessageBox.Show("获取文件信息失败:" + ex.Message, "操作失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
  146. downloadFiles = null;
  147. return downloadFiles;
  148. }
  149. }
  150. //获取指定的文件的内容
  151. public string GetFileContent(string filename)
  152. {
  153. FtpWebRequest reqFTP;
  154. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpServerIP + "/" + filename));
  155. reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
  156. reqFTP.UseBinary = true;
  157. reqFTP.Credentials = new NetworkCredential(ftpUser, ftpPwd);
  158. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  159. Stream ftpStream = response.GetResponseStream();
  160. int bufferSize = GetFileContentLength(filename);
  161. byte[] buffer = new byte[bufferSize];
  162. ftpStream.Read(buffer, 0, bufferSize);
  163. ftpStream.Close();
  164. return Encoding.Default.GetString(buffer);
  165. }
  166. //获取指定文件的内容的字节长度
  167. public int GetFileContentLength(string filename)
  168. {
  169. FtpWebRequest reqFTP;
  170. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpServerIP + "/" + filename));
  171. reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
  172. reqFTP.UseBinary = true;
  173. reqFTP.Credentials = new NetworkCredential(ftpUser, ftpPwd);
  174. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  175. Stream ftpStream = response.GetResponseStream();
  176. List<byte> buf = new List<byte>();
  177. while (ftpStream.ReadByte() != -1)
  178. {
  179. buf.Add((byte)ftpStream.ReadByte());
  180. }
  181. ftpStream.Close();
  182. return buf.ToArray().Length * 2;
  183. }
  184. /// <summary>
  185. /// 获取FTP上指定文件的大小
  186. /// </summary>
  187. /// <param name="filename">文件名</param>
  188. /// <returns>文件大小</returns>
  189. public long GetFileSize(string filename)
  190. {
  191. FtpWebRequest reqFTP;
  192. long fileSize = 0;
  193. try
  194. {
  195. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpServerIP + "/" + filename));
  196. reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
  197. reqFTP.UseBinary = true;
  198. reqFTP.Credentials = new NetworkCredential(ftpUser, ftpPwd);
  199. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  200. Stream ftpStream = response.GetResponseStream();
  201. fileSize = response.ContentLength;
  202. ftpStream.Close();
  203. response.Close();
  204. }
  205. catch (Exception ex)
  206. {
  207. MessageBox.Show("获取文件大小时,出现异常:\n" + ex.Message, "获取文件大小失败!", MessageBoxButtons.OK, MessageBoxIcon.Error);
  208. }
  209. return fileSize;
  210. }
  211. /// <summary>
  212. /// 实现ftp下载操作
  213. /// </summary>
  214. /// <param name="fileName">远程文件名</param>
  215. public string Download(string fileName)
  216. {
  217. FtpWebRequest reqFTP;
  218. try
  219. {
  220. FileStream outputStream = new FileStream(DownLoadTo + @"\" + fileName, FileMode.Create);
  221. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpServerIP + "/" + fileName));
  222. reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
  223. reqFTP.UseBinary = true;
  224. reqFTP.Credentials = new NetworkCredential(ftpUser, ftpPwd);
  225. reqFTP.UsePassive = true;
  226. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  227. Stream ftpStream = response.GetResponseStream();
  228. long cl = response.ContentLength;
  229. int bufferSize = 2048;
  230. int readCount;
  231. byte[] buffer = new byte[bufferSize];
  232. readCount = ftpStream.Read(buffer, 0, bufferSize);
  233. while (readCount > 0)
  234. {
  235. outputStream.Write(buffer, 0, readCount);
  236. readCount = ftpStream.Read(buffer, 0, bufferSize);
  237. }
  238. ftpStream.Close();
  239. outputStream.Close();
  240. response.Close();
  241. return DownLoadTo + @"\" + fileName;
  242. }
  243. catch (Exception ex)
  244. {
  245. MessageBox.Show(ex.Message);
  246. return "";
  247. }
  248. }
  249. public string DownLoadFromSharePath(string URL,string fileName)
  250. {
  251. //目标路径
  252. string targetPath = FTPInf;
  253. //var file = Directory.GetFiles(targetPath);
  254. string sourceFile = Path.Combine(URL);
  255. string destFile = Path.Combine(DownLoadTo, fileName);
  256. //不存在文件的话进行创建
  257. if (!Directory.Exists(DownLoadTo))
  258. Directory.CreateDirectory(DownLoadTo);
  259. //将文件复制到指定位置
  260. try
  261. {
  262. File.Copy(sourceFile, destFile, true);
  263. }
  264. catch {
  265. MessageBox.Show("标签文件更新失败,不在指定维护路径"+ URL + "中或已被占用","提示",MessageBoxButtons.OK,MessageBoxIcon.Warning);
  266. }
  267. return destFile;
  268. }
  269. /// <summary>
  270. /// 删除文件
  271. /// </summary>
  272. /// <param name="fileName"></param>
  273. public void Delete(string fileName)
  274. {
  275. try
  276. {
  277. FtpWebRequest reqFTP;
  278. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpServerIP + "/" + fileName));
  279. reqFTP.KeepAlive = false;
  280. reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
  281. reqFTP.UseBinary = true;
  282. reqFTP.Credentials = new NetworkCredential(ftpUser, ftpPwd);
  283. reqFTP.UsePassive = true;
  284. string result = String.Empty;
  285. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  286. long size = response.ContentLength;
  287. Stream datastream = response.GetResponseStream();
  288. StreamReader sr = new StreamReader(datastream);
  289. result = sr.ReadToEnd();
  290. sr.Close();
  291. datastream.Close();
  292. response.Close();
  293. //Buffer.Log(string.Format("Ftp文件{1}删除成功!", DateTime.Now.ToString(), fileName));
  294. }
  295. catch (Exception ex)
  296. {
  297. throw ex;
  298. }
  299. }
  300. }
  301. }