ftpOperater.cs 15 KB

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