-1

我有listBox1并且listBox2其中加载了目录中的一些文件。最初,当我加载表单时,我禁用了listBox1和的按钮listBox2

当目录中没有文件时,我想禁用 button1 listBox1和 button2 listBox2

但是我想启用buttons相应的listBox1listBox2如果目录中有单个文件并且文件是否有任何更改。

我如何使用 FileSystemWatcher??? 我需要一些想法来执行此操作。

private void PopulateListBox(ListBox lsb, string Folder, string FileType)
{
  DirectoryInfo dinfo = new DirectoryInfo(Folder);
  FileInfo[] Files = dinfo.GetFiles(FileType);
  foreach (FileInfo file in Files)
  {
    lsb.Items.Add(file);
  }
}

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
  FileInfo file = (FileInfo)listBox1.SelectedItem;
  string path = file.FullName;
  DisplayFile(path);
}

private void button1_Click(object sender, EventArgs e)
{

}


private void fileSystemWatcher1_Changed(object sender, FileSystemEventArgs e)
{

}

我已经在这里初始化了一个方法,从这里我该如何进行???

public void filesystemwatcher()
{
  FileSystemWatcher watcher = new FileSystemWatcher();
  watcher.Path = @"C:\LoadFiles\";                      
}
4

1 回答 1

2

您可以将 BindingList 与 FileSystemWatcher 一起使用:

BindingList<string> _Files = new BindingList<string>();

public Form1() {
  InitializeComponent();

  _Files.ListChanged += new ListChangedEventHandler(Files_ListChanged);
  fileSystemWatcher1.Deleted += fileSystemWatcher1_Deleted;
  fileSystemWatcher1.Created += fileSystemWatcher1_Created;
  fileSystemWatcher1.Renamed += fileSystemWatcher1_Renamed;
  fileSystemWatcher1.Path = @"C:\TestLoadFiles\";

  foreach (string f in Directory.GetFiles(fileSystemWatcher1.Path)) {
    _Files.Add(Path.GetFileName(f));
  }
  listBox1.DataSource = _Files;
}

private void Files_ListChanged(object sender, ListChangedEventArgs e) {
  button1.Enabled = (_Files.Count > 0);
}

private void fileSystemWatcher1_Renamed(object sender, RenamedEventArgs e) {
  _Files[_Files.IndexOf(e.OldName)] = e.Name;
}

private void fileSystemWatcher1_Deleted(object sender, FileSystemEventArgs e) {
  _Files.Remove(e.Name);
}

private void fileSystemWatcher1_Created(object sender, FileSystemEventArgs e) {
  _Files.Add(e.Name);
}
于 2012-05-15T13:54:40.227 回答