时间:2021-07-01 10:21:17 帮助过:18人阅读
FtpHelper.cs 类代码 using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace WindowsService1 { public class FtpHelper { private FtpWebRequest ftpRequest = null; private FtpWebResponse ftpResponse = null; private Stream ftpStream = null; /// <summary> /// Get Filelist Name /// </summary> /// <param name="userId">ftp userid</param> /// <param name="pwd">ftp password</param> /// <param name="ftpIP">ftp ip</param> /// <returns></returns> public string[] GetFtpFileName(string userId, string pwd, string ftpIP, string filename) { string[] downloadFiles; StringBuilder result = new StringBuilder(); try { ftpRequest = (FtpWebRequest)FtpWebRequest.Create(ftpIP + "/" + filename); ftpRequest.Credentials = new NetworkCredential(userId, pwd); ftpRequest.UseBinary = true; ftpRequest.UsePassive = true; ftpRequest.KeepAlive = true; ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory; ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); ftpStream = ftpResponse.GetResponseStream(); StreamReader ftpReader = new StreamReader(ftpStream); string line = ftpReader.ReadLine(); while (line != null) { result.Append(line); result.Append("\n"); line = ftpReader.ReadLine(); } result.Remove(result.ToString().LastIndexOf(‘\n‘), 1); ftpReader.Close(); ftpStream.Close(); ftpResponse.Close(); ftpRequest = null; return result.ToString().Split(‘\n‘); } catch (Exception ex) { downloadFiles = null; return downloadFiles; } } public string[] GetFtpFileName(string userId, string pwd, string ftpIP) { string[] downloadFiles; StringBuilder result = new StringBuilder(); try { ftpRequest = (FtpWebRequest)FtpWebRequest.Create(ftpIP + "/"); ftpRequest.Credentials = new NetworkCredential(userId, pwd); ftpRequest.UseBinary = true; ftpRequest.UsePassive = true; ftpRequest.KeepAlive = true; ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory; ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); ftpStream = ftpResponse.GetResponseStream(); StreamReader ftpReader = new StreamReader(ftpStream); string line = ftpReader.ReadLine(); while (line != null) { result.Append(line); result.Append("\n"); line = ftpReader.ReadLine(); } result.Remove(result.ToString().LastIndexOf(‘\n‘), 1); ftpReader.Close(); ftpStream.Close(); ftpResponse.Close(); ftpRequest = null; return result.ToString().Split(‘\n‘); } catch (Exception ex) { downloadFiles = null; return downloadFiles; } } /// <summary> ///从ftp服务器上下载文件的功能 /// </summary> /// <param name="userId"></param> /// <param name="pwd"></param> /// <param name="ftpUrl">ftp地址</param> /// <param name="filePath"></param> /// <param name="fileName"></param> public void DownloadFtpFile(string userId, string pwd, string ftpUrl, string filePath, string fileName) { FtpWebRequest reqFTP = null; FtpWebResponse response = null; try { String onlyFileName = Path.GetFileName(fileName); string downFileName = filePath + "\\" + onlyFileName; string url = "ftp://" + ftpUrl + "/" + fileName; if (File.Exists(downFileName)) { DeleteDir(downFileName); } FileStream outputStream = new FileStream(downFileName, FileMode.Create); reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(url)); reqFTP.Credentials = new NetworkCredential(userId, pwd); reqFTP.UseBinary = true; reqFTP.UsePassive = true; reqFTP.KeepAlive = true; reqFTP.Method = WebRequestMethods.Ftp.DownloadFile; response = (FtpWebResponse)reqFTP.GetResponse(); Stream ftpStream = response.GetResponseStream(); long cl = response.ContentLength; int bufferSize = 2048; int readCount; byte[] buffer = new byte[bufferSize]; readCount = ftpStream.Read(buffer, 0, bufferSize); while (readCount > 0) { outputStream.Write(buffer, 0, readCount); readCount = ftpStream.Read(buffer, 0, bufferSize); } ftpStream.Close(); outputStream.Close(); response.Close(); } catch (Exception ex) { throw ex; } } /// 基姆拉尔森计算公式计算日期 /// </summary> /// <param name="y">年</param> /// <param name="m">月</param> /// <param name="d">日</param> /// <returns>星期几</returns> public static string CaculateWeekDay(int y, int m, int d) { if (m == 1 || m == 2) { m += 12; y--; //把一月和二月看成是上一年的十三月和十四月,例:如果是2004-1-10则换算成:2003-13-10来代入公式计算。 } int week = (d + 2 * m + 3 * (m + 1) / 5 + y + y / 4 - y / 100 + y / 400) % 7; string weekstr = ""; switch (week) { case 0: weekstr = "星期一"; break; case 1: weekstr = "星期二"; break; case 2: weekstr = "星期三"; break; case 3: weekstr = "星期四"; break; case 4: weekstr = "星期五"; break; case 5: weekstr = "星期六"; break; case 6: weekstr = "星期日"; break; } return weekstr; } /// <summary> /// 返回不带后缀的文件名 /// </summary> /// <param name="fileName"></param> /// <returns></returns> public static string GetFirstFileName(string fileName) { return Path.GetFileNameWithoutExtension(fileName); } #region 删除指定目录以及该目录下所有文件 /// </summary><param name="dir">欲删除文件或者目录的路径</param> public static void DeleteDir(string dir) { CleanFiles(dir);//第一次删除文件 CleanFiles(dir);//第二次删除目录 } /// <summary> /// 删除文件和目录 /// </summary> ///使用方法Directory.Delete( path, true) private static void CleanFiles(string dir) { if (!Directory.Exists(dir)) { File.Delete(dir); return; } else { string[] dirs = Directory.GetDirectories(dir); string[] files = Directory.GetFiles(dir); if (0 != dirs.Length) { foreach (string subDir in dirs) { if (null == Directory.GetFiles(subDir)) { Directory.Delete(subDir); return; } else CleanFiles(subDir); } } if (0 != files.Length) { foreach (string file in files) { File.Delete(file); } } else Directory.Delete(dir); } } #endregion } public class ChannelListInfo { // public string ChannelID { get; set; } public string WeekDate { get; set; } public string ChannelTV { get; set; } public string ChannelName { get; set; } public string ChannelType { get; set; } public string ChannelSummary { get; set; } // public string ChannelImg { get; set; } public DateTime ChannelStartDate { get; set; } public DateTime ChannelEndDate { get; set; } // public DateTime? AddTime { get; set; } public DateTime? ChannelPlayDate { get; set; } } public class ChannelTvListInfo { public string TVName { get; set; } public string LastWriteTime { get; set; } } // Custom comparer for the Product class public class ProductComparer : IEqualityComparer<ChannelTvListInfo> { // Products are equal if their names and product numbers are equal. public bool Equals(ChannelTvListInfo x, ChannelTvListInfo y) { //Check whether the compared objects reference the same data. if (Object.ReferenceEquals(x, y)) return true; //Check whether any of the compared objects is null. if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null)) return false; //Check whether the products‘ properties are equal. return x.TVName == y.TVName && x.LastWriteTime == y.LastWriteTime; } // If Equals() returns true for a pair of objects // then GetHashCode() must return the same value for these objects. public int GetHashCode(ChannelTvListInfo product) { //Check whether the object is null if (Object.ReferenceEquals(product, null)) return 0; //Get hash code for the Name field if it is not null. int hashProductName = product.TVName == null ? 0 : product.TVName.GetHashCode(); //Get hash code for the Code field. int hashProductCode = product.LastWriteTime.GetHashCode(); //Calculate the hash code for the product. return hashProductName ^ hashProductCode; } } }
C# 利用FTP自动下载xml文件后利用 FileSystemWatcher 监控目录下文件变化并自动更新数据库
标签:length class sed sam eth iter stat ber error