1. 程式人生 > >C# FileSystemWatcher監聽資料夾

C# FileSystemWatcher監聽資料夾

用FileSystemWatcher監聽資料夾

很久沒有寫windows服務了,這兩天做了一個監聽資料夾的服務,用FileSystemWatcher類監聽資料夾,如果有新建立的xml檔案,就把xml檔案反序列化進資料庫。用dapper操作資料庫。

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.IO;
using Dapper;
using System.Data.SqlClient;

namespace HGHService
{
    using Models;
    public partial class HGHService1 : ServiceBase
    {
        readonly string connString = "user id=sa;password=***;Data Source=192.123.**.**;Initial Catalog=***";
        public HGHService1()
        {
            InitializeComponent();
            
        }
        private void WatcherStrat(string path, string filter)
        {
            //DirectoryInfo di = new DirectoryInfo(path);
            //if (di.GetFiles().Length + di.GetDirectories().Length == 0)
            //{
                ////目錄為空
            //}
            FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.Path = path;
            watcher.Filter = filter;
            //watcher.Changed += new FileSystemEventHandler(OnChanged);
            watcher.Created += new FileSystemEventHandler(OnCreated);
            watcher.EnableRaisingEvents = true;
            watcher.NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.LastWrite
           | NotifyFilters.FileName | NotifyFilters.DirectoryName; // NotifyFilters.Attributes | NotifyFilters.CreationTime | NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastAccess
                                   //| NotifyFilters.LastWrite | NotifyFilters.Security | NotifyFilters.Size;
            watcher.IncludeSubdirectories = true;
        }
        private void OnCreated(object source, FileSystemEventArgs e)
        {
            //Console.WriteLine("檔案新建事件處理邏輯 {0}  {1}  {2}", e.ChangeType, e.FullPath, e.Name);
            #region === 讀取檔案內容 ===
            string xmlStr = string.Empty;
            while (true)
            {
                try
                {
                    using (Stream stream = File.Open(e.FullPath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
                    {
                        if (stream != null)
                            break;
                    }
                    System.Threading.Thread.Sleep(500);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(string.Format("Output file {0} not yet ready ({1})", e.Name, ex.Message));
                }
            }

            using (FileStream fs = new FileStream(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                using (StreamReader sr = new StreamReader(fs, Encoding.UTF8))
                {
                    xmlStr = sr.ReadToEnd();
                }
            }
            #endregion
            //SEQ_NO
            if (xmlStr.Contains("SEQ_NO") && xmlStr.Contains("DEC_DATA"))
            {
                DEC_DATA xmldata = Tools.DeSerialize<DEC_DATA>(xmlStr, Encoding.UTF8);
                H200 h200 = new H200();
                #region 反序列化成功
                if (xmldata != null)
                {
                    #region 判斷重複
                    using (IDbConnection connection = new SqlConnection(connString))
                    {
                        string sql = "select * from [H200] where [SEQ_NO]='" + xmldata.DEC_RESULT.SEQ_NO + "' and [CHANNEL]='" + xmldata.DEC_RESULT.CHANNEL + "'"
                            + " and [NOTICE_DATE]='" + xmldata.DEC_RESULT.NOTICE_DATE + "'";
                        if (connection.Query<H200>(sql).ToList().Any())
                            return;
                    }                    
                    #endregion
                    h200.SEQ_NO = xmldata.DEC_RESULT.SEQ_NO;
                    h200.ENTRY_ID = xmldata.DEC_RESULT.ENTRY_ID;
                    h200.NOTICE_DATE = xmldata.DEC_RESULT.NOTICE_DATE;
                    h200.CHANNEL = xmldata.DEC_RESULT.CHANNEL;
                    h200.NOTE = xmldata.DEC_RESULT.NOTE;
                    h200.DECL_PORT = xmldata.DEC_RESULT.DECL_PORT;
                    h200.AGENT_NAME = xmldata.DEC_RESULT.AGENT_NAME;
                    h200.DECLARE_NO = xmldata.DEC_RESULT.DECLARE_NO;
                    h200.TRADE_CO = xmldata.DEC_RESULT.TRADE_CO;
                    h200.CUSTOMS_FIELD = xmldata.DEC_RESULT.CUSTOMS_FIELD;
                    h200.BONDED_NO = xmldata.DEC_RESULT.BONDED_NO;
                    h200.I_E_DATE = xmldata.DEC_RESULT.I_E_DATE;
                    h200.PACK_NO = xmldata.DEC_RESULT.PACK_NO;
                    h200.BILL_NO = xmldata.DEC_RESULT.BILL_NO;
                    h200.TRAF_MODE = xmldata.DEC_RESULT.TRAF_MODE;
                    h200.VOYAGE_NO = xmldata.DEC_RESULT.VOYAGE_NO;
                    h200.NET_WT = xmldata.DEC_RESULT.NET_WT;
                    h200.GROSS_WT = xmldata.DEC_RESULT.GROSS_WT;
                    h200.D_DATE = xmldata.DEC_RESULT.D_DATE;
                    h200.RESULT_INFO = xmldata.RESULT_INFO;
                }
                #endregion
                h200.H200Id = Guid.NewGuid().ToString();
                h200.H200_FullName = e.FullPath;// Path.Combine(e.FullPath, e.Name);// e.FullPath+e.Name;
                h200.H200_Data = xmlStr;
                using (IDbConnection connection = new SqlConnection(connString))
                {
                    StringBuilder sb = new StringBuilder();
                    sb.Append("insert into [H200](");
                    sb.Append("[H200Id],[SEQ_NO],[ENTRY_ID],[NOTICE_DATE],[CHANNEL],[NOTE],[DECL_PORT],[AGENT_NAME]");
                    sb.Append(",[DECLARE_NO],[TRADE_CO],[CUSTOMS_FIELD],[BONDED_NO],[I_E_DATE],[PACK_NO],[BILL_NO],[TRAF_MODE]");
                    sb.Append(",[VOYAGE_NO],[NET_WT],[GROSS_WT],[D_DATE],[RESULT_INFO],[H200_FullName],[H200_Data]");
                    sb.Append(") values (");
                    sb.Append("@H200Id,@SEQ_NO,@ENTRY_ID,@NOTICE_DATE,@CHANNEL,@NOTE,@DECL_PORT,@AGENT_NAME");
                    sb.Append(",@DECLARE_NO,@TRADE_CO,@CUSTOMS_FIELD,@BONDED_NO,@I_E_DATE,@PACK_NO,@BILL_NO,@TRAF_MODE");
                    sb.Append(",@VOYAGE_NO,@NET_WT,@GROSS_WT,@D_DATE,@RESULT_INFO,@H200_FullName,@H200_Data");
                    sb.Append(")");
                    if (connection.Execute(sb.ToString(), h200) > 0)
                    {
                        //File.Delete(e.FullPath);
                    }
                }
            }
            
        }

        protected override void OnStart(string[] args)
        {
            WatcherStrat(@"D:\t1", "*.xml");
        }

        protected override void OnStop()
        {
        }
    }
}