Hi, I have a list box that on form load displays file names inside a directory using this code

DirectoryInfo di2 = new DirectoryInfo(path);
                    foreach (FileInfo fi2 in di2.GetFiles())
                    {
                        listBox1.Items.Add(fi2.Name);
                    }

Which works fine, however i have another function on my form which adds files to the directory read by the listbox, is there a way to update the listbox? . i was thinking maybe a timer but i'm not sure.
Thanks.

Recommended Answers

All 4 Replies

I forgot to mention, i tried adding a 'refresh' button which just repeated the above code but that led to duplicates with every button press, i can't figure out how to get rid of them.

Thanks that helped but i seem to be having trouble, this is on my save button.

FileSystemWatcher watcher = new FileSystemWatcher();
                watcher.Path = path;

And then this is on my filewatcher created

private void fileSystemWatcher1_Created(object sender, FileSystemEventArgs e)
        {
            listBox1.Items.Add(e.Name);
        }

I think it should work but whever i add a file to the folder watching nothing happens.

Ensure you have all the appropriate NotifyFilter and Filter settings. Here is an excerpt from the MSDN example:

/* Watch for changes in LastAccess and LastWrite times, and
           the renaming of files or directories. */
        watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
           | NotifyFilters.FileName | NotifyFilters.DirectoryName;
        // watch all files
        watcher.Filter = "*.*";

You might also try adding NotifyFilters.CreationTime to the above flag attributes, but it would seem unnecessary due to the LastWrite attribute.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.