ftpOperater.cs 15 KB

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