ftpOperater.cs 15 KB

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