Last active
July 5, 2017 14:18
-
-
Save JokerMartini/c5fbe9789db767cb5215 to your computer and use it in GitHub Desktop.
C#: This snippet is used to search through a directory and build a treeview list of nodes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.ComponentModel; | |
using System.Data; | |
using System.Drawing; | |
using System.IO; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
using System.Windows.Forms; | |
namespace WindowsFormsApplication1 | |
{ | |
public partial class Form1 : Form | |
{ | |
public static List<string> formats = new List<string>(); | |
public Form1() | |
{ | |
InitializeComponent(); | |
//add userfolder | |
List<string> Directories = new List<string>(); | |
Directories.Add(System.Environment.GetEnvironmentVariable("USERPROFILE")); | |
// get formats accepted | |
formats.Add(".txt"); | |
formats.Add(".png"); | |
PopulateTree(Directories, formats); | |
} | |
static bool IsValidFileFormat(string filename, List<string> formats) | |
{ | |
if (formats.Count == 0) return true; | |
string ext = Path.GetExtension(filename); | |
bool results = formats.Any(fileType => fileType.Equals(ext, StringComparison.OrdinalIgnoreCase)); | |
return results; | |
} | |
public static TreeNode CreateDirectoryNode(DirectoryInfo directoryInfo) | |
{ | |
TreeNode directoryNode = new TreeNode(directoryInfo.Name); | |
foreach (var directory in directoryInfo.GetDirectories()) | |
{ | |
try | |
{ | |
directoryNode.Nodes.Add(CreateDirectoryNode(directory)); | |
} | |
catch (UnauthorizedAccessException) { } | |
} | |
foreach (var file in directoryInfo.GetFiles()) | |
{ | |
if (IsValidFileFormat(file.FullName, formats)) | |
{ | |
TreeNode node = new TreeNode(file.FullName); | |
node.ForeColor = Color.Red; | |
directoryNode.Nodes.Add(node); | |
} | |
} | |
return directoryNode; | |
} | |
public void PopulateTree(List<string> directories, List<string> formats) | |
{ | |
// main collection of nodes which are used to populate treeview | |
List<TreeNode> treeNodes = new List<TreeNode>(); | |
foreach (string directoryPath in directories) | |
{ | |
if (Directory.Exists(directoryPath)) | |
{ | |
DirectoryInfo directoryInfo = new DirectoryInfo(directoryPath); | |
treeNodes.Add(CreateDirectoryNode(directoryInfo)); | |
} | |
} | |
treeView1.Nodes.AddRange(treeNodes.ToArray()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment