2012-05-15 62 views
-1

我有listBox1listBox2,它們加載了目錄中的一些文件。最初,當我加載表單我禁用了listBox1listBox2的按鈕。用於列表框的FileSystemWatcher

當目錄中沒有文件時,我想禁用按鈕1的listBox1和按鈕2 listBox2

但是,如果目錄中有單個文件,並且文件中有任何更改,我想啓用相應的listBox1listBox2buttons。如何使用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\";      
} 
+0

你嘗試處理給onChanged或OnCreated事件? – Vertigo

+0

「c#use filesystemwatcher」的一個快速谷歌帶來這個:http://www.techrepublic.com/article/use-the-net-filesystemwatcher-object-to-monitor-directory-changes-in-c/6165137 –

+0

@ Thorsten Dittmar:努力工作。 – linguini

回答

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); 
} 
+0

:錯誤「fileSystemWatcher1_Deleted」匹配委託「System.IO.FileSystemEventHandler」 – linguini

+0

@KarthikRANGARAJ無過載我所做的只是地方FileSystemWatcher組件我的形式,其默認的名稱'fileSystemWatcher1',並添加您在看到該代碼帖子。該表格顯然包含一個ListBox和一個Button。 – LarsTech

+0

明白了,現在沒關係。檢查整個代碼。 – linguini