I have created a file Explorer in C# to select a file from a list of directories, however I have limited knowledge on how to specify the file type itself.
I only want .xls
files to be displayed, not all files displayed. How do I go about this? I currently have:
TreeNode newSelected = e.Node;
listView1.Items.Clear();
DirectoryInfo nodeDirInfo = (DirectoryInfo)newSelected.Tag;
ListViewItem.ListViewSubItem[] subItems;
ListViewItem item = null;
foreach (DirectoryInfo dir in nodeDirInfo.GetDirectories())
{
item = new ListViewItem(dir.Name, 0);
subItems = new ListViewItem.ListViewSubItem[]
{new ListViewItem.ListViewSubItem(item, "Directory"),
new ListViewItem.ListViewSubItem(item,
dir.LastAccessTime.ToShortDateString())};
item.SubItems.AddRange(subItems);
listView1.Items.Add(item);
}
foreach (FileInfo file in nodeDirInfo.GetFiles())
{
item = new ListViewItem(file.Name, 1);
subItems = new ListViewItem.ListViewSubItem[]
{ new ListViewItem.ListViewSubItem(item, "File"),
new ListViewItem.ListViewSubItem(item,
file.LastAccessTime.ToShortDateString())};
item.SubItems.AddRange(subItems);
listView1.Items.Add(item);
}
You could change your 2nd for loop to:
foreach (var file in nodeDirInfo.GetFiles())
{
if (file.Extension == ".xls")
{
// Do the stuff with the file
}
}
or
foreach (var file in nodeDirInfo.GetFiles()
.Where(file =>
string.Equals(file.Extension, ".xls")))
{
// Do the stuff with the file
}
For your purposes I would recommend using OpenFileDialog
, as it sounds like you just need the user to select a file from the directory:
var openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = @"C:\Path\To\Directory\";
openFileDialog1.Filter = "Excel Files (*.xls)|*.xls";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
var selectedFilePath = openFileDialog1.FileName;
}