Hello everyone,
This is my first post and I was wondering if anyone can help me. I am trying to populate user selected files (file path) into a treeview, but whenever I select multiple files from the same sub folder, it displays the root path and sub folder for each file.
private void BrowseButton_Click(object sender, EventArgs e)
{
// open file dialog method - set initial directory, filter and title
OpenFileDialog.InitialDirectory = @"E:\AIR";
OpenFileDialog.Filter = "Data Sources (*.txt, *.html)|*.txt*;*.html|All Files|*.*";
OpenFileDialog.Title = "Select a file";
// calls open file dialog method
if (OpenFileDialog.ShowDialog() == DialogResult.OK)
{
// places selected files into an array
fileArray = OpenFileDialog.FileNames;
foreach (string file in fileArray)
{
string folderDirectory = System.IO.Path.GetDirectoryName(file);
string[] folders = folderDirectory.Split('\\');
RichTextBox1.Text = folderDirectory;
TreeNode rootNode = new TreeNode();
// checks if rootNode contains key
if (treeView1.Nodes.ContainsKey(folders[0]))
{
rootNode = treeView1.Nodes[folders[0]];
}
else
{
rootNode = treeView1.Nodes.Add(folders[0]);
}
// for loop which calls AddNode function
for (int i = 1; i < folders.Length; i++)
{
rootNode = AddNode(rootNode, folders[i]);
}
// gets and adds file name to root node
string fileNode = System.IO.Path.GetFileName(file);
rootNode.Nodes.Add(fileNode);
}
}
}
private TreeNode AddNode(TreeNode node, string key)
{
if (node.Nodes.ContainsKey(key))
{
return node.Nodes[key];
}
else
{
return node.Nodes.Add(key, key);
}
}
The output is like this:
E:
+--AIR
+--Test Files
+-- .txt file 1
E:
+--AIR
+--Test Files
+-- .txt file 2
If someone can help, I would greatly appreciate this.