c# – How to pass a file names to a DataGridView using FolderBrowserDialog?

Question:

How can I pass the name of the files found inside the selected folder?

So far I've only managed to make it get the file's path and pass it to the DataGridView and now I want to make it pass the name too.

Here's the code part for FolderBrowserDialog .

private void btnDiretorio_Click(object sender, EventArgs e)
    {

        this.grvShowFile.Rows.Clear();
        folderBrowserDialog.RootFolder = Environment.SpecialFolder.DesktopDirectory;
        folderBrowserDialog.SelectedPath = openFileDialog.InitialDirectory;
        folderBrowserDialog.ShowNewFolderButton = true;
        openFileDialog.Filter = "Form (*.frm)|*.frm|" + "All files (*.*)|*.*";
        DialogResult result = folderBrowserDialog.ShowDialog();

        if (result == DialogResult.OK)
        {
            List<string> selectedPath = listaArquivos(folderBrowserDialog.SelectedPath);
            foreach (string s in selectedPath)
            {
                grvShowFile.Rows.Add(s);
            }
        }
    }

    public List<string> listaArquivos(string dir)
    {
        List<string> lstDirs = Directory.GetDirectories(dir).ToList();
        List<string> lstFiles = Directory.GetFiles(dir).ToList();
        List<string> lstFilesAux = new List<string>();

        foreach(string ldir in lstDirs)
            lstFilesAux = listaArquivos(ldir);

        lstFiles.AddRange(lstFilesAux);
        return lstFiles;
    }

And if you can also tell me how I can make it look for only the files that are in the filter, I would be grateful.

Answer:

To get only the file name contained in a path, the Path.GetFileName() method is used.

It will probably do something like this:

List<string> selectedPath = listaArquivos(folderBrowserDialog.SelectedPath);
foreach (string s in selectedPath) {
    grvShowFile.Rows.Add(Path.GetFileName(s));
}

I put it on GitHub for future reference .

Scroll to Top