佛利斯博客

VB.NET / C# 监控文件夹中文件是否被创建/删除/改名

创建 VB 或 C# 小程序来监视文件夹中文件是否被创建、改名、内容变动(文件大小变动)或删除。主要是利用 FileSystemWatcher() 函数来达到目的的。

今天这段代码稍微有些复杂,我把所有代码都复制出来了,大家直接复制粘贴就可以了。自己想提取的话,自行动手。

VB 代码

Imports System
Imports System.IO

Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim m_watcher = New System.IO.FileSystemWatcher()
        m_watcher.Filter = "*.*"
        m_watcher.Path = "C:\temp\"
        m_watcher.NotifyFilter = (NotifyFilters.LastAccess Or NotifyFilters.LastWrite Or NotifyFilters.FileName Or NotifyFilters.DirectoryName)
        AddHandler m_watcher.Changed, AddressOf OnChanged
        AddHandler m_watcher.Created, AddressOf OnChanged
        AddHandler m_watcher.Deleted, AddressOf OnChanged
        AddHandler m_watcher.Renamed, AddressOf OnRenamed
        m_watcher.EnableRaisingEvents = True
    End Sub

    Private Shared Sub OnChanged(source As Object, e As FileSystemEventArgs)
        MessageBox.Show("File: " & e.FullPath & " " & e.ChangeType)
    End Sub

    Private Shared Sub OnRenamed(source As Object, e As RenamedEventArgs)
        MessageBox.Show(e.OldFullPath & " has changed name to " & e.FullPath)
    End Sub
End Class

VB代码的 MessageBox 提示变动类型只显示数字,自己加个字符串替换一下即可。我这就懒的改了,自己知道什么原理就成了。

C# 代码

using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Security.Permissions;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        private System.IO.FileSystemWatcher m_watcher;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Form1 obj = new Form1();
            obj.Hide();
            m_watcher = new System.IO.FileSystemWatcher();
            m_watcher.Filter = "*.*";
            m_watcher.Path = @"C:\temp\";
            m_watcher.IncludeSubdirectories = true;
            m_watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
            m_watcher.Created += new FileSystemEventHandler(OnChanged);            
            m_watcher.Deleted += new FileSystemEventHandler(OnChanged);
            m_watcher.Changed += new FileSystemEventHandler(OnChanged);
            m_watcher.Renamed += new RenamedEventHandler(OnRenamed);
            m_watcher.EnableRaisingEvents = true;
        }

        public void OnChanged(object sender, FileSystemEventArgs e)
        {
            MessageBox.Show("File: " + e.FullPath + " " + e.ChangeType);
        }

        public void OnRenamed(object sender, RenamedEventArgs e)
        {
            MessageBox.Show(e.OldFullPath + " has changed name to " + e.FullPath);
        }

    }
}
退出移动版