Lane will
Lane will

Reputation: 73

Items are not appearing in Listview

I apologize if I'm missing something simple, I'm still learning. This is my first attempt at recursion. this program is supposed to do the following, First I open my FileBrowserDialog, then the listview Populates with the file names within the folder selected. However, when I select the folder it fills the listview but I cannot see any names and my listview freezes. the reason I know it fills is the scroll bar adjusts. this is my code:

#region FileHandlers



    void FolderSearch(string sFol)
    {
        try
        {
            foreach (string d in Directory.GetDirectories(sFol))
            {
                foreach (string f in Directory.GetFiles(d))
                {

                    listView1.Items.Add(f);
                }
                FolderSearch(d);
            }
        }
        catch (System.Exception excpt)
        {
            MessageBox.Show(excpt.Message);
        }
    }

    public void ChooseFolder()
    {
        string pPath;

        if(folderBrowserDialog1.ShowDialog() == DialogResult.OK)
        {
            pPath = folderBrowserDialog1.SelectedPath;

            FolderSearch(pPath);
        }
    }

    #endregion
    void Button1Click(object sender, EventArgs e)
    {
        ChooseFolder();
    }

Upvotes: 1

Views: 74

Answers (1)

Djordje
Djordje

Reputation: 457

Your code skips the selected folder and it will only get files from subfolders within selected folder, because you are first calling GetDirectories method, if you don't have subfolders within selected folder or your subfolders dont have files, it will get nothing.

Try this

 void FolderSearch(string sFol)
    {
        try
        {
            foreach (string f in Directory.GetFiles(sFol))
            {
                listView1.Items.Add(f);
            }

            foreach (string d in Directory.GetDirectories(sFol))
            {                  
                FolderSearch(d);
            }
        }
        catch (System.Exception excpt)
        {
            MessageBox.Show(excpt.Message);
        }
    }

and also if you want only file name use GetFileName method from System.IO.Path class. listView1.Items.Add(Path.GetFileName(f));

Upvotes: 1

Related Questions