我有listBox1
和listBox2
,它们从目录中加载了一些文件。最初,当我加载表单时,我已禁用listBox1
和listBox2
的按钮。
如果目录中没有文件,我想禁用listBox1
和button2 listBox2
的button1。
但是如果目录中有单个文件且文件中有任何更改,我想启用相应buttons
和listBox1
的{{1}}。
如何使用listBox2
执行此操作?我需要一些想法来执行此操作。
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)
{
}
答案 0 :(得分: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);
}