Windows Forms: How to make a File Browser in C#

How to make a File Browser in C# using ListView to contain the file name with icons

Step 1: Click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "FileBrowser" and then click OK

c# file browser

Step 2: Design your file browser form as below

file browser in c#

Step 3: Add code to your project

You should create a list to contain the file names

List<string> listFiles = new List<string>();

Add a click event handler to btnOpen

private void btnOpen_Click(object sender, EventArgs e)
{
    //Clear all items
    listFiles.Clear();
    listView.Items.Clear();
    //Open folder browser dialog
    using (FolderBrowserDialog fbd = new FolderBrowserDialog() { Description = "Select your path." })
    {
        if (fbd.ShowDialog() == DialogResult.OK)
        {
            //Set path to textbox
            txtPath.Text = fbd.SelectedPath;
            foreach (string item in Directory.GetFiles(fbd.SelectedPath))
            {
                //Add image to imagelist
                imageList.Images.Add(System.Drawing.Icon.ExtractAssociatedIcon(item));
                FileInfo fi = new FileInfo(item);
                listFiles.Add(fi.FullName);//Add file name to list
                //Add file name and image to listview
                listView.Items.Add(fi.Name, imageList.Images.Count - 1);
            }
        }
    }
}

Click the listview control, select event SelectedIndexChanged then add below code

private void listView_SelectedIndexChanged(object sender, EventArgs e)
{
    if (listView.FocusedItem != null)
        Process.Start(listFiles[listView.FocusedItem.Index]); //Open process
}

VIDEO TUTORIALS

 

Related Posts