(转)如何监视文件夹变化

 

如何监视文件夹变化

 使用工具箱中 组件中的FileSystemWatcher 控件

看下 对它的说明

public class FileSystemWatcher : System.ComponentModel.Component
System.IO 的成员
摘要:
 侦听文件系统更改通知,并在目录或目录中的文件发生更改时引发事件。
 
再来看下代码的处理
 
        private void button1_Click_1(object sender, System.EventArgs e)
        {//浏览文件夹
            if(this.folderBrowserDialog1.ShowDialog()==DialogResult.OK)
            {
                if(this.folderBrowserDialog1.SelectedPath.Trim()!="")
                {
                    this.textBox1.Text=this.folderBrowserDialog1.SelectedPath.Trim();
                }
            }
        }
 
        private void button2_Click(object sender, System.EventArgs e)
        {//开始监视文件系统变化情况
            if(!System.IO.Directory.Exists(this.textBox1.Text))
            {
                MessageBox.Show("选择的不是一个文件夹","信息提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
                return;
            }
            this.fileSystemWatcher1.Path=this.textBox1.Text;
            MessageBox.Show(this.textBox1.Text+"已经处于被监视状态!","信息提示",MessageBoxButtons.OK,MessageBoxIcon.Information);

        }
 
        private void fileSystemWatcher1_Changed(object sender, System.IO.FileSystemEventArgs e)
        {//发生改变
           this.richTextBox1.Text+=e.FullPath.ToString()+"  发生改变!\n";
        }
 
        private void fileSystemWatcher1_Created(object sender, System.IO.FileSystemEventArgs e)
        {//新增
            this.richTextBox1.Text+="\n刚刚新增:"+e.FullPath.ToString();
        }
 
        private void fileSystemWatcher1_Deleted(object sender, System.IO.FileSystemEventArgs e)
        {//删除
            this.richTextBox1.Text+="\n刚刚删除:"+e.FullPath.ToString();
        }
 
        private void fileSystemWatcher1_Renamed(object sender, System.IO.RenamedEventArgs e)
        {//更名
            this.richTextBox1.Text+="\n刚刚更名:"+e.FullPath.ToString();
        }
 
看看一些事件的说明
 
 
 
public string Path [  get,  set ]
    System.IO.FileSystemWatcher 的成员

 
 
摘要:
 获取或设置要监视的目录的路径。
public event System.IO.FileSystemEventHandler Changed
    System.IO.FileSystemWatcher 的成员
 
摘要:
 当更改指定 System.IO.FileSystemWatcher.Path 中的文件和目录时发生。
 
 
 
public event System.IO.FileSystemEventHandler Created
    System.IO.FileSystemWatcher 的成员
 
摘要:
 当在指定 System.IO.FileSystemWatcher.Path 中创建文件和目录时发生。
public event System.IO.FileSystemEventHandler Deleted
    System.IO.FileSystemWatcher 的成员
 
摘要:
 删除指定 System.IO.FileSystemWatcher.Path 中的文件或目录时发生。
public event System.IO.RenamedEventHandler Renamed
    System.IO.FileSystemWatcher 的成员
 
摘要:
 重命名指定 System.IO.FileSystemWatcher.Path 中的文件或目录时发生。
原文地址:https://www.cnblogs.com/fjchenqian/p/1381598.html