ftpOperater.cs 16 KB

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