Populate a 2 dimensional List From Directory.GetFiles

126 views Asked by At

I currently am populating a dropdown list with the contents of all files in a directory using this code:

 string[] filePaths = Directory.GetFiles(@ConfigurationManager.AppSettings["File_Path"]
 .ToString(), "*.txt");

            if (filePaths == null || filePaths.Length == 0)
            {
                ddlFiles.Items.Insert(0, new ListItem("NO TEXT FILES CURRENTLY AVAILABLE !"));
            }
            else
            {
                ddlFiles.DataSource = filePaths;
                ddlFiles.DataBind();
                ddlFiles.Items.Insert(0, new ListItem("PLEASE SELECT A TEXT FILE"));
            }

The problem is that the dropdown will show the complete path to the files. I just want to show the file name and extension. I figure that I could use a two dimensional List, and load the path into one dimension. I could then just loop through that dimension and parse everything after the last "\" to get just the file name and write it back to the other dimension in that List. This would result in a List with two dimensions, one with paths and one with file names. I could then load the dropdown from the 2 dimensional List using the path for the DataValueField and the file name for the DataTextField.

My problem is that I can't get a 2 Dimensional List to load from Directory.GetFiles. Can someone post an example? Also, how do I specifically address each dimension in the List to load the Value/Text attributes of the dropdown list?

Thank You in advance for your help!

1

There are 1 answers

1
Nikolay On

I don't think you need multi-dimensional arrays here.. You can just separate "Value" and "Text". That is, data binding supports value and text, using "DataValueField" and "DataTextField", you could just use those. Means, first you get a list of pairs, and then bind them to the value/text of the item, like this:

var filePaths = Directory.GetFiles(@ConfigurationManager.AppSettings["File_Path"].ToString(), "*.txt")
    .Select(path => new
    {
        Path = path, 
        Name = Path.GetFileName(path)
    }).ToArray();

if (filePaths == null || filePaths.Length == 0)
{
    ddlFiles.Items.Insert(0, new ListItem("NO TEXT FILES CURRENTLY AVAILABLE !"));
}
else
{
    ddlFiles.DataSource = filePaths;
    ddlFiles.DataValueField = "Path";
    ddlFiles.DataTextField = "Name";
    ddlFiles.DataBind();
    ddlFiles.Items.Insert(0, new ListItem("PLEASE SELECT A TEXT FILE"));
}