日期:2014-05-18  浏览次数:20677 次

FileSystemWatcher 的用法!
我用textbox1找到要显示的文件,在listBox1中显示其所以的子目录!
  private void button1_Click(object sender, EventArgs e)
  {
  DialogResult dr = folderBrowserDialog1.ShowDialog();
  if (DialogResult.Cancel == dr)
  return;
  textBox1.Text = folderBrowserDialog1.SelectedPath;
  FileSystemWatcher watch = new FileSystemWatcher(textBox1.Text);
  watch.NotifyFilter = (NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName);
  watch.Changed += new FileSystemEventHandler(OnChanged);//我每次运行到这里就直接过了,没有调用OnChanged
  watch.EnableRaisingEvents = true;

  }
  private void OnChanged(object source, FileSystemEventArgs e)
  {
  WatcherChangeTypes changType = e.ChangeType;
  string item = "";
  item += DateTime.Now.ToString() + "---";
  item += e.FullPath + ":";
  item += changType.ToString();
  listBox1.Items.Add(item);

  }

这是什么原因呢?

------解决方案--------------------
FileSystemWatcher watch;

private void button1_Click(object sender, EventArgs e)
{
DialogResult dr = folderBrowserDialog1.ShowDialog();
if (DialogResult.Cancel == dr)
return;
textBox1.Text = folderBrowserDialog1.SelectedPath;
watch = new FileSystemWatcher(textBox1.Text);
watch.IncludeSubdirectories = true;
watch.NotifyFilter = (NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName);
watch.Changed += new FileSystemEventHandler(OnChanged);//我每次运行到这里就直接过了,没有调用OnChanged
watch.EnableRaisingEvents = true;

}
private void OnChanged(object source, FileSystemEventArgs e)
{
WatcherChangeTypes changType = e.ChangeType;
string item = "";
item += DateTime.Now.ToString() + "---";
item += e.FullPath + ":";
item += changType.ToString();
listBox1.Items.Add(item);






------解决方案--------------------
//我每次运行到这里就直接过了,没有调用OnChanged

??

OnChanged只有在有文件更新的时候才会触发。
------解决方案--------------------
它并不是立刻执行onchange的事件,而是在watch.EnableRaisingEvents = true; 之后开始监控你的目的文件夹
当有对应的事件发生的时候发执行onchange的代码啊,比如你在那个文件夹里新建一个文件