using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Linq; using System.ServiceProcess; using System.Text; using System.Timers; using CDCopyTest.Log; using System.IO; using System.Configuration; using System.Net; using QMAPP.FJC.Entity.Basic; using QMAPP.FJC.BLL.FileCopy; using QMAPP.FJC.Entity.FileCopy; using QMAPP.FJC.BLL.Basic; namespace CDCopyTest { public partial class Service1 : ServiceBase { #region 获取配置文件 //获取服务器设备存储文件地址 String ServicePath = ConfigurationManager.AppSettings["DCSFilesPath"].ToString(); //服务器用户名 String ServiceUser = ConfigurationManager.AppSettings["DCSNetUser"].ToString(); //服务器密码 String ServicePwd = ConfigurationManager.AppSettings["DCSNetPwd"].ToString(); //获取本地存储文件地址 String LocalPath = ConfigurationManager.AppSettings["LOCAL_FILEPATH"].ToString(); //监控设备编号 String LogPath = ConfigurationManager.AppSettings["LOCAL_FILEPATH"].ToString(); Timer timer; #endregion public Service1() { InitializeComponent(); } protected override void OnStart(string[] args) { timer = new Timer(3000); //timer.Interval = 3000; timer.Elapsed += new ElapsedEventHandler(Timer_Elapsed); timer.Enabled = true; } public void OnStart() { bool status = false; status = connectState(ServicePath, ServiceUser, ServicePwd); if (status) { Download("服务进行"); } } protected override void OnStop() { this.timer.Enabled = false; } /// /// /// /// /// protected void Timer_Elapsed(object sender, ElapsedEventArgs e) { bool status = false; status = connectState(ServicePath, ServiceUser, ServicePwd); if (status) { Download("服务进行"); } else { LogFileAccess.WriteLogFile("成都业纳激光切文件抓取失败1" + "---" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); } } #region 连接远程共享文件夹 /// /// 连接远程共享文件夹 /// /// 远程共享文件夹的路径 /// 用户名 /// 密码 /// public static bool connectState(string path, string userName, string passWord) { bool Flag = false; Process proc = new Process(); try { proc.StartInfo.FileName = "cmd.exe"; proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardInput = true; proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.RedirectStandardError = true; proc.StartInfo.CreateNoWindow = true; proc.Start(); string dosLine = "net use " + path + " " + passWord + " /user:" + userName; proc.StandardInput.WriteLine(dosLine); proc.StandardInput.WriteLine("exit"); while (!proc.HasExited) { proc.WaitForExit(1000); } string errormsg = proc.StandardError.ReadToEnd(); proc.StandardError.Close(); if (string.IsNullOrEmpty(errormsg)) { Flag = true; } else { LogFileAccess.WriteLogFile("成都业纳激光切文件抓取失败2" + errormsg + "---" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); throw new Exception(errormsg); } } catch (Exception ex) { LogFileAccess.WriteLogFile("成都业纳激光切文件抓取失败3" + ex.Message + ex.Source + "---" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); throw ex; } finally { proc.Close(); proc.Dispose(); } return Flag; } #endregion /// /// 下载文件方法 /// /// 被下载的文件地址(服务器地址包括文件) /// 另存放的路径(本地需要存储文件的文件夹地址) public static void Download(string str) { string filePath = AppDomain.CurrentDomain.BaseDirectory + "Log.txt"; StreamWriter sw = null; if (!File.Exists(filePath)) { sw = File.CreateText(filePath); } else { sw = File.AppendText(filePath); } sw.Write(str + DateTime.Now.ToString() + Environment.NewLine); sw.Close(); //获取本地存储文件地址 String LocalfilePath = ConfigurationManager.AppSettings["LOCAL_FILEPATH"].ToString(); //获取服务器设备存储文件地址 String ServicePath = ConfigurationManager.AppSettings["DCSFilesPath"].ToString(); // LogFileAccess.WriteLogFile("服务启动" + "---" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); //获得总文件夹下的子目录信息 DirectoryInfo root = new DirectoryInfo(ServicePath); var dics = root.GetDirectories(); //日期命名的文件夹 string dateDay = DateTime.Now.ToString("yyyyMMdd"); //最新的文件服务器路径 string FullPath = ServicePath + @"\" + dateDay; //带文件名称的完整服务器路径 try { string[] files = Directory.GetFiles(FullPath, "*.txt"); foreach (string file in files) { WebClient client = new WebClient(); //文件名称 string fileName = file.Substring(file.LastIndexOf("\\") + 1); //另存为本地盘地址 string path = LocalfilePath + @"\" + dateDay; //本地dns string hostname = Dns.GetHostName(); //设备信息 MachineInfoBLL macBLL = new MachineInfoBLL(); List listMachine = macBLL.GetAllList(new MachineInfo { EQUIPMENT_TYPE_CODE = ConfigurationManager.AppSettings.Get("DCS_ET_JENOPTIK_TYPE") }); FileCopyRecordBLL bll = new FileCopyRecordBLL(); FileCopyRecord record = new FileCopyRecord(); foreach (MachineInfo machine in listMachine) { //**********************校验****************** List list = bll.GetAllList(new FileCopyRecord { RECORD_FILENAME = fileName, EQUIPMENT_INFO_KEY = machine.PID, FILE_HOSTNAME = hostname }); //无记录,插入数据库中 if (list.Count <= 0) { #region "把文件复制记录写入数据库" record.RECORD_KEY = Guid.NewGuid().ToString(); record.RECORD_EQUIPMENT_CODE = machine.MACHINECODDE; record.RECORD_EQUIPMENT_TYPE_CODE = machine.EQUIPMENT_TYPE_CODE; record.RECORD_EQUIPMENT_DIRECTORY = path; record.RECORD_KEYWORDS = machine.MACHINECODDE; record.RECORD_COPY_DATETIME = DateTime.Now; record.RECORD_READFLAG = "0"; record.RECORD_FILENAME = fileName; record.EQUIPMENT_INFO_KEY = machine.PID; record.FILE_LASTWRITETIME = DateTime.Now.ToString(); record.FILE_HOSTNAME = hostname; bll.Insert(record); #endregion #region //拷贝文件至本地 FileStream inFileStream = new FileStream(file, FileMode.Open); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } FileStream outFileStream = new FileStream(path + @"\" + fileName, FileMode.OpenOrCreate); byte[] buf = new byte[inFileStream.Length]; int byteCount; while ((byteCount = inFileStream.Read(buf, 0, buf.Length)) > 0) { outFileStream.Write(buf, 0, byteCount); } inFileStream.Flush(); inFileStream.Close(); outFileStream.Flush(); outFileStream.Close(); #endregion Console.WriteLine(file); } } } //文件名称 DirectoryInfo root2 = new DirectoryInfo(FullPath); foreach (FileInfo f in root2.GetFiles()) { Console.WriteLine(f.Name); } } catch (Exception ex) { LogFileAccess.WriteLogFile("服务启动失败4" + "---"+ ex + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); } } } }